img-1

An easy way to defer jQuery in WordPress

img-2

Defer jQuery is probably the most popular JavaScript library that makes a developer’s life easy writing cross-browser compatible JS code. Basically, it uses many native or vanilla JavaScript APIs under the hood and makes complex tasks like DOM traversal, event handling, and XHR (a JavaScript API to create AJAX requests) super easy and mostly exception-free.

defer jQuery comes bundled with WordPress core ever since the WordPress platform evolved. That is the reason, even many themes or plugins developed for WordPress have a dependency on jQuery. While starting from Twenty Nineteen default theme, WP has stopped loading jQuery in the frontend, around 76% of popular WordPress themes still have a dependency on the defer jQuery library.

How defer jQuery reduces PageSpeed score

While the popular library makes life easy, it comes with a performance cost. To understand this, let’s first try to understand how an HTML page and related assets such as JavaScript code are downloaded, evaluated, and executed.

jquery-javascript-execution

The heavier the script, the more delay it will cause in finishing the page load event. And this is not just determined by the file size on the network, but more by how CPU intensive is the piece of code sitting inside the library. This is the reason defer jQuery contributes to high Total Blocking Time (TBT) and Time to Interactive (TTI) hence having a significant impact on your overall PageSpeed performance score.

The async and defer JS features

async and defer are two special attributes for a <script> tag to indicate the browser when it should download and evaluate the source file of the script. There is a basic difference between how these two directives work.

  • async – The browser can download the script file and execute it without waiting for the HTML parser to be completed. Hence, the script download may happen in parallel with HTML parsing, and then getting executed as soon as it can be. This gives a good performance advantage as the HTML parsing continues most of the time. It creates problem when the scipt wants to modify the DOM, as it may not be available. The second problem is, that it does not gurantee the sequence or order of execution. So, if you have included two <script src=”something.js” async> tags, the second one may execute before the first one.
  • defer – Whith defer, the JS files are downloaded by the browser without halting the HTML parsing, and executed in the same order once HTML is parsed and all JS scripts are downloaded. However, the oder is followed only for those sripts where the ‘defer’ tag was used. Hence, any inline JS or external JS without the ‘defer’ attribute amy get executed first.

This SO thread has good content related to async and defer.

defer jQuery
Picture source: https://stackoverflow.com/questions/10808109/script-tag-async-defer

Can you defer jQuery?

The short answer is not easy. Now that we have learned how async and defer work, none of them seems suitable for the main jQuery library. One primary reason is many plugins and inline scripts are dependent on jQuery. There are tons of plugins for different purposes such as creating image carousels or sliders, form validation and submission, making fancy dropdowns on top of default <select> element, interactive tabular data, and charts, maps, etc.

You may often see common dependent statements like $( document ).ready() . If the defer jQuery is not available before any other script that is dependent on it, the browser will start throwing errors such as “jQuery is not defined” because the browser won’t understand what the other script is referring to.

One possible solution is, can include defer jQuery as the first-ever JS block on a page with the ‘defer’ attribute and make sure to defer all other following scripts to guarantee the order of execution. But because many theme developers and plugin developers write it differently, it may not be strictly followed and all inline <script> blocks need to be removed as the defer attributes are only supported for external scripts.

How to defer jQuery to improve PageSpeed score?

Method 1 – Hold jQuery event

Consider the below code example, where the scripts are fed to the browser in an unrecognizable way first, say by setting script type as “anything-random” instead of “text/javascript” and then changing the type once the page is loaded-

<script type="my-deffered-code" src="path-to-jquery.js" onload="window.jQuery.holdReady(true);"></script>
<script type="my-deffered-code" src="path-to-plugin2.js"></script>
<script type="my-deffered-code">alert("inline js");</script>

In the first line of the above code, where were are loading jQuery, the ‘onload’ event will hold firing the jQuery ready event till all files are loaded.

<script type="text/javascript">
window.addEventListener("load", function(e){
	document.querySelectorAll('[type="my-deffered-code"]').forEach(element=>{
		element.setAttribute("type", "text/javascript");
	});
});
window.jQuery.holdReady(false);// release the hold
<script>

This is not a production-ready code but gives a fair idea of some key concepts involved in deferring all JS code including the heavy library we are focusing on.

Method 2 – RabbitLoader optimizer

While most of the JS optimization plugins available can help you defer loading all JS files except defer jQuery, Rabbit Loader has a sophisticatedly developed algorithm to take care of all JavaScript loading including the jQuery to minimize the performance penalty and boost page loading time. A free plugin is available for WordPress website owners which requires no technical knowledge or configuration to improve all Core Web Vitals matrices for your website and help you achieve the best PageSpeed Insights score. It makes your visitors and search engines love your page.

Along with defer jQuery, Rabbit Loader can defer the execution of other JavaScript plugins, CSS stylesheets, heavy font files, and images used in your WordPress website.

Search

Related
    No related articles found.
img-5