DEV Community

Cover image for Oh, It's you jQuery
Sebastian Ślęczka
Sebastian Ślęczka

Posted on

Oh, It's you jQuery

Hey! I need jQuery compatibility on some projects. How can I make defer loading jQuery? I have to remember that some plugins load jQuery code directly in HTML

Top comments (3)

Collapse
 
piprees profile image
Pip Rees

We've used this to help us defer jQuery. I'm not the original author, but I can't find where we got it from right now. Sorry it's minified too. If i find the OP i'll post a follow up link.

<script>
// Allow jQuery to be loaded async...
window.jQueryLoader={boot:function(){void 0!==window.jQuery.fn?(jQueryLoader.bootInterval&&clearInterval(jQueryLoader.bootInterval),jQueryLoader.bootInterval=0,jQuery(jQueryLoader.unqueue)):jQueryLoader.bootInterval||(jQueryLoader.bootInterval=setInterval(function(){jQueryLoader.boot()},25))},bootInterval:null,booted:function(){return 0===jQueryLoader.bootInterval},queue:[],ready:function(e){return"function"==typeof e&&jQueryLoader.queue.push(e),jQueryLoader},unqueue:function(){for(var e=0;e<jQueryLoader.queue.length;e++)jQueryLoader.queue[e]();jQueryLoader.queue=[]}};if(void 0===window.jQuery)var jQuery=jQueryLoader.ready;
</script>

<!-- Now load jQuery from your preferred source with the defer or async attribute -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous" defer></script>

You essentially want to queue up the calls to jQuery.ready so that they execute after the page has loaded. This script creates a fake jQuery object, and repeatedly checks for the jQuery.fn property (which means that the jQuery library has loaded). Then it executes the .ready calls in the order they entered the queue.

<script>
// 
jQuery.ready(function() {
  var $ = jQuery;
  console.log('Your on-page jQuery components should load fine');
});
</script>

Try it out, it might need some tweaking but it gets the job done.

Collapse
 
sevastijan profile image
Sebastian Ślęczka

Thanks a lot!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.