Loading jQuery asynchronously

If you're reading this, you probably are already familiar with loading your JavaScript asynchronously, to improve your web page load times.

And, you have probably driven yourself crazy trying to figure out how to load the jQuery library asynchronously, while making sure your JavaScript that depends on jQuery, executes after jQuery has loaded.

This problem has been solved and packaged by this clever fellow: http://www.yterium.net/jQl-an-asynchronous-jQuery-Loader?lang=fr

But, why add yet another dependency to your site.

The method I propose requires you to host your jQuery library of choice locally, and modify to asynchronously load your scripts that depend on it.

This example jquery.min.js illustrates my point:

/*! jQuery v1.7.1 jquery.com | jquery.org/license */
(function(a,b){function cy ..........

/* added to load my jQuery depended scripts asynchronously, after jQuery has been loaded */

(function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = '/src/js/myJqueryCode.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

 

Now, simply load jQuery.min.js asynchronously, within your main template file. And, voila, all your scripts are deferred until after page load!

Subscribe

  • follow us in feedly


Tagged , .

Updated: 2012-01-19

Phil LaNasa
  • http://www.recuperodati299euro.it/ Robert

    Can you kindly provide an practical example?
    I’m using this jquery responsive navigation menu –> http://www.smartmenus.org/

    If I load jquery at bottom of the page, it won0t work properly.

    Thank you for sharing an complete working setup

    R.

    • lan99

      Right, it won’t work if you load jQuery asynchronously but load your smartmenus library in a blocking way beforehand.

      You will need to load the smartmenus library asyncrhonously within your jquery script.

      However, you’ll have to self-host jQuery to do this.

      If you want to use a CDN (as mentioned in your other comment), you might want to look at http://headjs.com/

      • http://www.recuperodati299euro.it/ Robert

        Thank you
        though in the past days I’ve found requirejs scipt library.

        I’m experiencing on both :-)

        • lan99

          RequireJS seems to be popular, as well as head.js for this type of thing. For a quick one-off requirement though, I like to avoid dependencies.

          It would be like loading jQuery just to do a single $(‘div’).hide() ;)