Load one time beside the $(document).ready(...) ? Jquery - javascript

I have a problem with triggering a function which needs to be loaded only one time.But I don't want to put it into:
jQuery(document).ready(function ($) {
});
I want to run it separate.
I have tried:
jQuery(document).one(function () {
myfunction();
});
and some other stuff.
But couldn't solve it.
UPDATE:
I have my webservice on ready():
jQuery(document).ready(function ($) {
PageMethods.myWebSer(suc, fail);
});
function suc(){
//I want to run my function here , but only one time
//Examplle
//jQuery(document).one(function () {
// myfunction();
// });
}
Thank You

Just add another ready or load function : you may have as many as you want, they will all be called in order :
jQuery(document).ready(function() {
// this will be run
});
jQuery(document).ready(function() {
// and this one too (after the other one)
});

It you want it to run onload use:
jQuery(window).load(function () {
// run
});
Keep in mind that ready fires before load.

Related

How to use jQuery to call a JavaScript function from another file

My question:
I have 2 files:
//Sub.js
function Second() {
//do something here
}
//Main.js
function One() {
//do something here
}
$(function() {
Second();
});
So basically, the function Second is too long; therefore, I want to move it to a Sub.js file and call it from the Main.js. The problem is this function ( function Second) has to be executed after function One because it gets some data from the function One output.
I don't know how to do this, please help.
If you specifically want to use jQuery,
$.getscript("Sub.js",function(){
Second();
});
<script src="/lib/Sub.js"></script>
<script src="/main.js"></script>
I think you should initialize firstly Sub.js before main.js in your head code.
Because whenever the page is first load js are intialize one by one.
You can include both the files in the page and on document ready call it sequentially:
$( document ).ready(function() {
var result = first();
second(result);
});
I was getting a similar problem. My solution was this. I was defining my function inside the .ready() callback. But The problem is that the functions is not accessible outside of its scope. To make this function available in the global scope (or through any object that is available in the global scope) is necessary declare outside the .ready() callback:
Wrong Way:
$(document).ready(function() {
function functionName () {
// ...
}
// ...
});
Right Way:
function functionName () {
// ...
}
$(document).ready(function() {
// ...
});

Why is my 'load' event/function not beeing executed after switching to jQuery 3?

Since I've upgraded from jQuery 1.x / jQuery 2.x to jQuery 3.x, my existing code will not be executed correctly anymore. Everything works fine, but the load event listener gets not triggered anymore or just sometimes:
$(function() {
$(window).on("load", function() {
// this line will never/occasionally be executed
console.log("window is loaded!");
});
});
The problem can be occur when using/switching to jQuery 3. It's because all ready states in the new jQuery 3 are now fully asynchron. This means, that there is no given order for your code to be executed.
Because of this, it could happen, that load is been triggered before your ready state has been executed. When your ready function now finally gets triggered, your load listener is too late and will not be executed.
jQuery Usage:
To change this behavior, just remove the ready state around your load event listener initialization. There is no need to encapsulate this with a ready function. You can initialize them without.
// $(function() {
$(window).on("load", function() {
// this line will now be executed again
console.log("window is loaded!");
});
// });
If you need or want to register both events, you can register the load event by yourself and decide inside the ready state what to do next.
// track the loading state by yourself
var windowLoaded = false;
$(window).on("load", function() {
windowLoaded = true;
});
$(function() {
function afterLoad() {
console.log("loaded");
}
// decide inside your ready state what to do
if( !windowLoaded ) {
$(window).on("load", afterLoad);
}
else {
afterLoad();
}
});
jQuery Plugins:
Another case would be jQuery plugins, that uses the load event too. For example:
(function($, window) {
$.fn.myPlugin = function() {
$(window).on("load", start);
function start() {
console.log("plugin initialized and window loaded");
}
};
})(jQuery, window);
If a developer/user now wraps the plugin initialization in a ready state the problem could happen again, just like explained before:
$(function() {
$("#element").myPlugin();
});
A solution would be to track the load event in your plugin on your own, to break out the ready state.
(function($, window) {
// track the loading state beside the plugin initialization
var windowLoaded = false;
$(window).on("load", function() {
windowLoaded = true;
});
$.fn.myPlugin = function() {
// decide inside your plugin how to start
if( !windowLoaded ) {
$(window).on("load", start);
}
else {
start();
}
function start() {
console.log("plugin initialized and window loaded");
}
};
})(jQuery, window);
Conclusion:
Even when this problem not happens to you, in your tests, you should change those code immediately, when using jQuery 3, because other users/different browser can run into this trouble. Others may got the problem, because it is asynchron, you could never know when/if your code gets executed ...

Native JavaScript document.ready - How to use bindReady()

I am looking for a native JavaScript solution to jQuery's document.ready(). Looking at this thread, CMS suggested to just use the code that jQuery used to implement their document.ready(). I am looking at bindReady() but am unsure how I would incorporate that into my code. I currently have something such as:
$(document).ready( function() {
console.log('foo');
});
Basically when you need to do is replace the lines that have
jQuery.ready();
with the name of the function you want to call. If you want something that works like jQuery's ready registering method, build a function that makes a queue. Loop through the queue when the "ready" is triggered.
You asked for more info so here is a quick and dirty example not using a timeout. This is NOT production ready, just a basic POC.
(function () {
var ready = {
_readyQueue: [],
_hasRun: false,
_docReadyCalled : function() {
this._hasRun = true;
this._execute();
},
_execute: function () {
var func;
while (this._readyQueue.length) {
func = this._readyQueue.shift();
func();
}
},
register: function (func) {
this._readyQueue.push(func);
if (this._hasRun) {
this._execute();
}
}
}
window.docReady = ready.register.bind(ready); //use what ever global namespace you want here
function bindReady() {
/* This would be that jQuery code, I am just use window load here so not so much code */
//Not all browser support this, quick and dirty for example
window.addEventListener('load', ready._docReadyCalled.bind(ready), false);
}
bindReady();
})();
/* waiting for DOM to be ready */
docReady(function () { console.log("here"); });
docReady(function () { console.log("there"); });
/* Showing what happens when you call docReady after it is ready */
docReady(function () { console.log("registering ready again"); docReady(function () { console.log("I am here!"); }); });
Your best bet is to probably avoid using DOM events entirely. It gets really complicated when you want to load as early as possible but want to be certain it isn't too early. This is an easy and 100% reliable technique to execute code as soon as the DOM has completed loading:
<html>
<head>
<!-- head content, blah, blah, blah -->
<script>
var ready = function() {
// Put everything in this function that you want to run when the page loads
nowTheDomIsLoaded();
console.log('foo');
};
</script>
</head>
<body>
<!-- page content, blah, blah, blah -->
<script>ready();</script>
</body>
</html>
Basically you put everything you want run in a function (e.g. ready()) and the very last thing you do before the closing </body> tag is you execute that function. Because everything in the <body> has been parsed you know the DOM is loaded, and this doesn't take any special library.

How to do asyncrhonous jQuery.get() before $(window).load()?

I want a SVG file to be loaded in a variable before $(window).load() will be fired.
I load the file using jQuery.get(). The problem is, that this function works asynchronously and by the time, when the SVG file is read, the $(window).load() is already invoked.
So I have following code:
var data;
$(document).ready(function () {
jQuery.get(
"my.svg",
function (_data) {
data = _data;
},
'text');
});
$(window).load( function () {
alert(data);
});
The alert will show "undefined". If it will be invoked later (after 5 seconds for example) then it will show the content of the SVG file.
Any suggestions? Thanks!
I agree that setInterval would probably be the solution you want IF you want to do stuff the hard way because you can never tell how long an AJAX request is going to take.
I would recommend restructuring your code to be more like this:
<script>
$(document).ready(function () {
//this can remain async: TRUE
jQuery.get(
"my.svg",
function (_data) {
//call function to do something to svg file
//if you are relying on the SVG to be there in order to call an action
//then why not wait for the SVG to load first and then call the action
svgAction(_data);
},
'text');
function svgAction(img_code){
//do something with img code now
}
});
</script>

How to get a javascript function to execute only once on dom ready

I'm getting alerted "hi" over and over again, how do I get it to do it once and stop:
function doSomething() {
alert('hi');
}
$(function() {
doSomething();
});
// Fired once when document is ready
$(document).one('ready', function () {
doSomething();
});
Using .one ensures this is done only once and not repeatedly.It is okay to put several document.ready event listeners (if you need other events to execute multiple times) as long as you do not overdo it, for the sake of readability.
.one is especially useful when you want the alert to appear the first time a web page is opened or when a mobile application is installed the first time.
I think you include your JS file multiple times from the HTML. Clean up your HTML.
Using:
$(function(){
});
is perfectly normal. Using more verbose form have no benefit. If you are writing a plugin, you might want to do this:
function($){
// $ always refers to jQuery here
...
}(jQuery);
// $ might not be defined here in compatibility mode.
Try with:
window.onload = function() {
doSomething();
}
Are you looking to do something like this?:
$(document).ready(function() {
doSomething();
});
The best way is ... with using cookie - like this:
$(document).ready(function () {
if ($.cookie("blocker") == 1) {
//your code or without code;
return;
} else {
//your code for first time
$.cookie("blocker", 1, {
expires: 1 / 24 / 60 //time, this is one minut
});
}
});
This code is good if you have smarty on your page
Raul is right, it would help to have the code...
But based on my experience with this, what you want is something more along the lines of:
var doSomething = function() {
alert('hi');
}
$(document).ready(function () {
doSomething();
});
You might want to stick to the more verbose style:
function doSomething() {
alert('hi');
}
$(document).ready(function() {
doSomething();
});

Categories