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!

Tags:

4 Comments

    1. 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/

        1. 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() 😉

Leave a Reply

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