Jenna
Jenna

Reputation: 25

Defer loading javascript

So i've read through a few tutorials but i'm still confused on how to do this proper.

My site is oaktreehealth.ca I have too many javascript files loading above the fold and I would like to defer any that do not need to load right away.

I have read this tutorial (and a great site overall!): https://varvy.com/pagespeed/defer-loading-javascript.html

Here are my questions:

  1. How do I include multiple files? Do I just create mutiple instances of the code he used? Or can I combine it all into one?

  2. How do I know what files I should defer? Some are obvious to me, others i'm not sure. Should I trial and error and see how it loads each time?

  3. I am using wordpress, so is this still a good way of doing it? Or is there another way where I can load it into my functions.php doc?

  4. Using this tool: https://varvy.com/tools/js/ I can see all my external scripts. If I add them in the defer code he used, do I use the full path? How can I find that for each script?

  5. Thank you so much! I know some of this must be very noob-y questions!

Upvotes: 1

Views: 1973

Answers (3)

Mark Gavagan
Mark Gavagan

Reputation: 1172

Regarding #2 of the question ("How do I know what (javascript) files I should defer?"), follow these steps:

(1) Use https://developers.google.com/speed/pagespeed/insights/ (2) Click "Show how to fix" under "Eliminate render-blocking JavaScript and CSS in above-the-fold content" (3) Look for the list of "Render-blocking JavaScript" for the scripts that should be deferred or otherwise addressed.

source: https://varvy.com

Upvotes: 0

Walid Raihan
Walid Raihan

Reputation: 36

Specific instructions

<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "defer.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
  1. Copy above code.

  2. Paste code in your HTML just before the </body> tag (near the bottom of your HTML file).

  3. Change the "defer.js" to the name of your external JS file.

  4. Ensure the path to your file is correct. Example: if you just put "defer.js", then the file "defer.js" must be in the same folder as your HTML file

Upvotes: 2

thatidiotguy
thatidiotguy

Reputation: 8991

If you look at wp_enqueue_script method here:

https://codex.wordpress.org/Function_Reference/wp_enqueue_script

You will see that the third argument is an array of scripts that the script you are loading depends on. If you do this for all your script files, WordPress will automatically load your JavaScript in the correct order.

Upvotes: 2

Related Questions