Skip to content

Wait for async JQuery to load

Moving JQuery to loading asynchronously can greatly improve your site’s loading time, but can cause issues with any scripts you may have on your site that are dependent on JQuery.  To wait until the document is ready to be manipulated you can usually just use

1
2
3
$(function() {
  // Handler for .ready() called.
});

But, $ may not be available if you’re loading JQuery asynchronously.  So you need to change that to wait until JQuery is available using vanilla JavaScript

1
2
3
4
5
6
7
8
9
10
var jqready = function(method) {
    if (window.$) {
        $(function() { method(); });
    } else {
        setTimeout(function() { jqready(method) }, 50);
    }
};
jqready(function() {
  //ready to use JQuery!
});

But, that’s a bit buky so here is a minified version

1
2
3
4
var jqready = (m)=>{(window.$)?($(()=>{m()}):(setTimeout(()=>{jqready(m)}, 50))};
jqready(function() {
  //ready to use JQuery!
});

Reference:
https://stackoverflow.com/questions/7486309/how-to-make-script-execution-wait-until-jquery-is-loaded
https://api.jquery.com/ready/

Published inJavaScriptScripting

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *