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.
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.
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.
This SO thread has good content related to async and defer.
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.
<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.
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.