Home Web Development JavaScript Fool-Proof jQuery Initialization

Get social!

I do a lot of coding using jQuery. One hurdle I would often run into resulted from page speed optimizations where I would load jQuery asynchronously, to make Google happy (and we *must* make Google happy). The problem, in a nutshell, was that my javascript code would fire off before jQuery was done loading. So this wouldn't work:

$(function() {
   $('#something').on('click', function(e) {
       // Insert killer code here.
   });
});

Worse, it would sometimes work, depending on how fast jQuery loaded.

If you've ever worked with WordPress and used a caching plugin, you've probably banged your head against this problem as well.

Here's how I finally solved this issue once and for all:

(function() {
     'use strict';
     function init() {
         if (!window.jQuery) {
             setTimeout(init, 100);
             return;
         }
         var $ = jQuery;

         // Your code goes here
     }
     init();
 })();

I've been using the above initialization routine for about 6 months now and I've had zero problems with it. Give it a try yourself and see what you think.

Leave a Reply

Bad Behavior has blocked 280 access attempts in the last 7 days.