The above is an example of loading Google Analytics on a site. This script loads on most of the pages on the internet. Most people don't know that this script will block the loading of your webpage and slow down your site.
This is why Google asks you to put it at the bottom of the webpage. When a browser reads the HTML of your page it goes through each line by line.
This will continue until the page has loaded.
How do we stop the blocking?
If we moved the contents of the Google Analytics script to a file called ga.js.
It would then load it like this:
Is this faster?
Well no, it is slower! The external file must download before it can run. It looks something like this:
It would be better if we could download the file without blocking the page.
This is what the async attribute does.
The async attribute will tell the browser to download in the background.
To make the script async you would add the attribute to the script tag like this:
The downloading of the file now does not block the HTML:
The file will download in the background and the HTML page continues to load. When the file has finished downloading it will run.
But when it runs it will block the page from loading so we are back to where we started with the inline script!
There is no guarantee that a.js will load before b.js. This is ok if the two files are separate and they don't rely on each other. Yet, if b.js relies on a.js then loading these scripts via async will break your site.
There is a better way.
The defer attribute is an attempt to fix all the issues mentioned above.
A script tag that is loading with defer looks like this:
The best thing about defer is that the order is also kept so if we have this:
Enable the default settings with the “Apply Defer” button. This will set up the default settings for deferring. It may be that some scripts break once you have applied the settings. If they do they you may need to add scripts to the exclusion section:
With this plugin, you want to make sure you load all scripts as external files in the <head> and add a defer attribute.
This may mean that you need to change some of the plugins and themes your site is using. If that is the case then you may need to talk to the theme developers and send them this article for guidance.
I also wanted to recommend a Shopify app that could help with the speed. Unfortunately, I was unable to find one that I could recommend.
You can, of course, do the above by hand to get defer working.
You would need to edit your theme.liquid file and find all the script tags on the page.
Then move them to the head and add defer. Always backup your site before doing manual edits!
The risk here will put off many people and I would love to recommend an easier option. If you have a recommendation I would love to test it and add it to this page.
My recommendation is to have all scripts loaded from external files. Then add the defer attribute to the script tags.