Daily Archives: December 19, 2012

Asynchronous JQuery loading using yepnope – almost there, but with quirks…

Today I stumpled upon a problem I was not (entirely) able to solve. I wanted to use the Javascript code printed below to load JQuery code asynchronously (using yepnope).

<script src="/scripts/modernizr-2.6.2.min.js" type="text/javascript"></script>
<script src="/scripts/yepnope.1.5.4-min.js" type="text/javascript"></script>
<script type="text/javascript">
	var docready = [], $ = function () { return { ready: function (fn) { docready.push(fn); } }; };
	yepnope({
		load: '//ajax.googleapis<em><strong>OFFLINE</strong></em>.com/ajax/libs/jquery/1.8.2/jquery.min.js',
		complete: function () {
			if (!window.jQuery) {
				yepnope({ load: '/scripts/jquery-1.8.2.min.js', complete: initJQuery });
			} else {
				initJQuery();
			}
		}
	});

	function initJQuery() {
		$ = window.jQuery;
		for (var index in docready) $(document).ready(docready[index]);
	}
</script>

The code works almost perfectly. The JQuery library is loaded from the Google CDN as requested, and when that one is not available, it falls back to local script loading. While the JQuery library is not yet loaded, I hold all calls to $(document).ready() to fire them when JQuery is loaded entirely. This works! However, I discovered that JQuery plugins do not work with this code, as they require the JQuery or $ object.

I know I should use the initJQuery function for plugin loading based on JQuery, but since some plugins get inserted by ASP.NET partial views or Rejuicer, this is not possible. Currently, I stick with late loaded synchronous JQuery plugin loading while still holding $(document).ready calls for later (guaranteed) execution. I am curious about your solutions though ;) .

PS. Ow, currently, the piece of code I use for now, is:

// in head:
<script type="text/javascript">var docready = [], $ = function () { return { ready: function(fn) { docready.push(fn); } }; };</script>

// just before </body> tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">window.jQuery || document.write('<script src="/scripts/jquery-1.8.2.min.js" type="text/javascript"><\/script>')</script>
<script type="text/javascript">
    // fire all preliminary $(document).ready(fn) calls immediately after jquery is loaded.
    $ = jQuery;
    for (n in docready) $(document).ready(docready[n]);
</script>