Use jQuery Without Loading Scripts in Document

So, I was working on a new theme for an OpenCart store I manage. Since creating it from scratch, I decided to adhere to suggestions from Bootstrap, Google and others that advise loading content-blocking scripts at the bottom of the page instead of in the <head>.

Of course, I ran into the same problem that probably has you reading this article.

How the hell am I supposed to use ‘jQuery’ or ‘$’ before the library is loaded?! Short answer, you can’t. You can however get around the problem with this solution.

Instead of relying on $(document).ready() which many of us have become accustomed, you can instead use traditional event listeners as a wrapper for your jQuery code further up in the DOM. Here is an example.

(function() {
	'use strict';
	window.addEventListener('load', function() {
		// All resources loaded
		$('#my-selector').on('click', function(event){
			//Do something
	}, false);

What we’re doing is wrapping our jQuery code that resides further up in the DOM with a ‘load’ event listener. Now the script will fire as soon as all resources are loaded. So even though our jQuery library was injected at the end of the document, the attempts to use ‘$’ will not fire until all resources have loaded.

Hint: You can use ‘window.addEventListener’ multiple times throughout the document. Each event is appended to the event listener’s queue.

In a perfect world we would simply include all of our scripts after jQuery before closing </body> tag. That is sometimes easier said than done 😛

Notes: The ‘DOMContentLoaded’ event would have been preferred, but since we cannot depend on HTML5 support 100%, ‘load’ was the lesser of 2 evils.

I tried using various shims, but none seem to work as expected for various 3rd-party plugins and this was a much faster solution than rewriting every one of them 😉

Leave a Reply

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