Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make script execution wait until jquery is loaded

People also ask

Does document ready wait for scripts?

We also can make this process faster in jQuery by using the $(document). ready() method. The $(document). ready() method only waits for the DOM to load, it doesn't wait for stylesheets, images, and iframes.

Which jQuery function prevents the code from running before the loading of the document finishes?

The Document Ready Event This is to prevent any jQuery code from running before the document is finished loading (is ready). It is good practice to wait for the document to be fully loaded and ready before working with it.

How do I run a jQuery script?

Declare the jQuery file path in the <script> tag inside the <head> tag section. Example 1: Create an HTML file & add below code into your HTML file.


Late to the party, and similar to Briguy37's question, but for future reference I use the following method and pass in the functions I want to defer until jQuery is loaded:

function defer(method) {
    if (window.jQuery) {
        method();
    } else {
        setTimeout(function() { defer(method) }, 50);
    }
}

It will recursively call the defer method every 50ms until window.jQuery exists at which time it exits and calls method()

An example with an anonymous function:

defer(function () {
    alert("jQuery is now loaded");
});

the easiest and safest way is to use something like this:

var waitForJQuery = setInterval(function () {
    if (typeof $ != 'undefined') {

        // place your code here.

        clearInterval(waitForJQuery);
    }
}, 10);

you can use the defer attribute to load the script at the really end.

<script type='text/javascript' src='myscript.js' defer='defer'></script>

but normally loading your script in correct order should do the trick, so be sure to place jquery inclusion before your own script

If your code is in the page and not in a separate js file so you have to execute your script only after the document is ready and encapsulating your code like this should work too:

$(function(){
//here goes your code
});

Yet another way to do this, although Darbio's defer method is more flexible.

(function() {
  var nTimer = setInterval(function() {
    if (window.jQuery) {
      // Do something with jQuery
      clearInterval(nTimer);
    }
  }, 100);
})();

You can try onload event. It raised when all scripts has been loaded :

window.onload = function () {
   //jquery ready for use here
}

But keep in mind, that you may override others scripts where window.onload using.


I have found that suggested solution only works while minding asynchronous code. Here is the version that would work in either case:

document.addEventListener('DOMContentLoaded', function load() {
    if (!window.jQuery) return setTimeout(load, 50);
    //your synchronous or asynchronous jQuery-related code
}, false);