Defer JavaScript parsing to load JQuery
When testing the website with Google Page Speed, it was found that I cannot get rid of Defer parsing of JavaScript
. I removed all javascript codes and left only small
<script defer type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.test').click(function(){
$(this).slideDown();
});
});
</script>
Or even without jquery code, just loading the jQuery file offline as
<script defer type="text/javascript" src="jquery.min.js"></script>
still get a warning for Defer parsing of JavaScript
.
source to share
I found this documentation page which reads:
To use this method, you must first define all JavaScript functions that are not actually used by the document before the onload event. For any file with more than 25 unclaimed functions, move all those functions to a separate external JS file. This may require some refactoring in your code to get around file dependencies. (For files with less than 25 unclaimed features, this is not worth the refactoring effort.)
Then you insert a JavaScript event listener at the beginning of the containing document, which causes the external file to load after the onload event. You can do this with any of the usual scripting tools, but we recommend a very simple scripting DOM element (to avoid cross-browser and single domain policy issues). Here's an example (where "deferredfunctions.js" contains functions that should be lazy loaded)
What I understand from this is: you have to "lazy-load" jQuery from an event handler onload
(see the link above for an example on how to do this).
source to share
@samsaffron wrote a good article on jQuery deferral - http://samsaffron.com/archive/2012/02/17/stop-paying-your-jquery-tax
source to share