Improve page loading performance when using jQuery
For the first version of projects I usually use a CMS with a theme. You get most of the content very fast and are still able to build a great API in the backend (with the right CMS). Themes usually still work with jQuery for a few effects. And jQuery is usually included in the head of the page which prevents the rendering of the page until it's loaded.
Depending on how the jQuery functions are called you can't just move it into the end of the body, because the jQuery functions might be called directly from the modules used somewhere in the page. To still be able to move the jQuery script to the bottom you basically have to prevent the call in the module from being triggered until the page is loaded.
Exactly for those instances there is a jQuery function $(document).ready()
. But of course we can't use this as we want to prevent the usuage of jQuery. There is a vanilla JS version which can be used instead:
document.addEventListener('DOMContentLoaded', function() {
// Your jQuery code which we want to prevent from running
}, false);
DOMContentLoaded
is now supported in all major browsers. Only IE 8 and below will not work.
I wrap all jQuery call in the templates with this and are able to put jQuery to the bottom of the page. This improves not just your ranking on Pagespeed but also the perceived performance of the page quite a lot.