Shopify Failed to Run the Script; Refresh or Try Again Later
Javascript performance and site speed is something everyone is concerned most. Your boss, your clients, everyone volition ask you to brand their online shop faster.
Equally an engineer, y'all'll take on the task, but will oftentimes find yourself in a code mess. The truth is that there is no silver bullet for site speed. Everything you try just gives you lot a fraction of a second of improvement. Finding that big improvement is like a treasure hunt.
In that location are many resources out there that will help guide yous to a solution, but every ecommerce platform has their challenges. In this commodity, I desire to propose an opinionated way to arroyo a site cleanup or refactor, starting with the unseemly: code organization. These six steps will assist you refactor a Shopify site to improve performance for Shopify merchants.
Grow your business with the Shopify Partner Programme
Whether yous offer marketing, customization, or spider web design and development services, the Shopify Partner Program will set you up for success. Join for free and access revenue share opportunities, tools to abound your business organisation, and a passionate commerce community.
Sign upward
ane. Figure out the virtually of import assets
Put yourself in the shoes of your client'south customers. What is the nearly important nugget that you need to run across in order to have a buying intention? Is it the ability to hit the buy button as presently as the page loads? Or is it the images showing what the products look like? In the majority of cases for ecommerce sites, it's the images showcasing the merchant's products that are most important—customers want to encounter what they're ownership.
This does change if the layout of the site is built with scripts, such as with single page apps, but for the purposes of this article, I will consider images the almost important avails on a site.
Y'all might also like: five Means to Improve Store Loading Times with Minification.
2. Keep Javascript to pre-adamant places
Before we strip away whatever unused code or start moving things effectually, we need to first define where Javascript should exist in whatever given document, using best performance practices. If you oasis't before, I advise reading the following resources:
- Google'south User-Axial Performance Metrics
- Google's Critical Rendering Path
If you've read these recommendations and are still lost about how to apply these recommendations to a Shopify site, follow along.
It's important to define where Javascript should exist, and then that we can spot where scripts shouldn't exist. There are merely three document areas that Javascript should be:
- Earlier the
</head>
tag - Afterwards the
<trunk>
tag - Before the
</trunk>
tag
Since we have identified images to be the most important asset, most Javascript should exist just before the </body>
tag, unless you accept very good reasons that it shouldn't. I will become through the reasoning for each script section.
"Be vigilant with where the script is placed fifty-fifty if you weren't the one who put it there."
Scripts allowed in the <head>
tag
Every third-political party vendor is going to tell you that their script needs to be at the very pinnacle of the <caput>
tag, but yous can give them the Terminator end hand. Scripts in the <head>
tag are render blocking. This means visitors volition not be able to see your beautiful website until the browser finishes parsing the content in your <head>
tag.
And so what scripts are allowed to exist in the <caput>
tag?
None.
The Shopify platform is a server-side framework using Liquid templating. The moment the source document is downloaded, there should be enough to render the most critical first render view, without whatsoever Javascript library needing to fill the gap (other than external CSS styles).
This doesn't hateful that no website should have scripts in the head
tag. Here are some examples where the scripts has legitimate reason to stay in the head:
- Unmarried folio apps. This is even better if the single folio app is hydrated with server side render.
- Inline scripts that don't trigger the downloading of external scripts, and performs time sensitive operations, such every bit:
<script type="text/javascript">
window.performance && window.performance.marking('head_start');
</script>
If there are scripts that practise need to be in the head, most of these should be just before the terminate of the closing </head>
tag. This ensures the site is optimized for browser resource prioritization optimization.
Ane more affair. There are misconceptions around the usage of scripts with async
or defer
. A script containing async
tells the browser that this script tin can be executed out of order, which makes this script non-render blocking. This means async
scripts execute the code as soon equally the script resources finishes downloading. Scripts with defer
pushes the execution of the Javascript to the end. However, both types of script announcement nonetheless impact the network bandwidth every bit downloaded resources, which we can leverage for operation to download the most important assets for first render.

Scripts allowed merely after the <trunk>
tag
Scripts in this area of the document are non the worst, but non the best either. Nosotros are however aiming for that first render view. The more we can push the download of external scripts later on, the amend. If you lot have a hero image or a drove of the latest products that you would like your visitor to come across, these should take priority over scripts that your visitors will never meet.
Browsers are systematic at resource prioritization. With scripts, browsers read the source certificate in a top-down order. If you have external scripts earlier the hero images, the external scripts will accept higher downloading priority than the hero images.
Scripts immune just before the </body>
tag
All scripts should be here.
This includes analytics scripts. What practiced are your analytics if your visitor's browser can't even go to this betoken of the folio?
Yous might too similar: How Lazy Loading can Optimize Your Shopify Theme Images.
3. Create site benchmarks
This is important. Without a benchmark, it is adjacent to impossible to tell if anything you do improves operation at all. We can contend that in that location are improvements that would make a huge divergence, but without proper measurements to understand what is happening, you could be making astonishing upgrades that no ane notices because they didn't move the metric your dominate is looking at.
To measure correctly, we will be using performance marks. This is a native Javascript API that is supported by most browsers in the world. Operation marks need to be in place right where they are executed. Specifically, we will exist measuring browser parse elapsing: the fourth dimension it takes for the browser to parse your Javascript.
Nosotros volition also make use of performance metrics that Chrome specifically has already collected for u.s.: paint.
performance.getEntriesByType('pigment');
Permit'southward place the operation marks at the proper place. First, we need to sympathise how to measure parse duration. To do this, identify performance marks like the following example in theme.liquid
.
You lot should also plough network throttling to Fast 3G and Disable cache in ChromeDevTools.
This should output a ton of metrics in ChromeDevTools. We'll focus on the parse metrics that we but implemented.

The time measurements here all resulted from loftier resolution timestamps in milliseconds. We tin can run into that the browser took 2563ms (ii.6 seconds on Fast 3G) to parse whatever is in the head tag. Nosotros can also see that the first pigment doesn't happen until the browser finishes parsing the head at 3522ms (startTime 959ms + duration 2563ms).
What does this mean? This means that your visitor waited through two and a one-half seconds (minus network fourth dimension) of white screen (aka nothing) before seeing your site.
Goal 1: Reduce parsing duration in the caput tag
Bold that you cannot remove any scripts on the site, your goal should be shifting metrics to optimize for operation. The outset paint metric is an important number to reduce for functioning. However, what'south holding information technology back isn't just what'due south in the head tag—parts of the body tag are also responsible for information technology, since the browser needs to parse it likewise before it can be rendered. And then, allow's also place performance markers inside the torso tag, like so:
Once this is added, nosotros should see the following:

We tin can run into from hither that beginning paint is sometime after parsing the caput, only before finishing parsing the body. If nosotros tin can reduce the parsing duration within the torso layout section, it should aid bring the first paint value down.
Goal 2: Reduce parsing duration in the body layout
With these ii goals in heed, let'southward sympathise a little math here. If nosotros cannot remove any lines of code in the project, what can we do to reduce the parsing duration in the head and trunk layouts? The respond is to push button the parsing elapsing to body scripts near the end of the body. Let the browser parse what is important starting time, and then that information technology can render information technology as shortly as information technology can.
Duration (Benchmark) | Desired result | |
Head | 2560 ms | Less time spent here |
Body layout | 2107 ms | Less fourth dimension spent here |
Stop body scripts | 17 ms | More time spent hither |
Starting time Pigment | A timing within torso layout | Faster |
Nosotros are trying to change the parsing duration inside each department to ultimality reduce the first pigment metric timing.
4. Clean up the scripts that don't belong anywhere
Imagine y'all're moving into a new business firm. You usually don't start past packing up the clothes you need to utilize everyday—y'all first with stuff you hardly ever use. As well, earlier we go and motion all the script to the bottom of the folio, allow's start with the scripts that don't vest anywhere: scripts in the middle of the body.
Some of these scripts take dependency on some Javascript libraries, which makes it really difficult to optimize for performance. It puts usa at risk of breaking the site if we motion these scripts to the bottom of the folio without because these dependencies. In Shopify themes, scripts in the middle of body includes any Javascript sitting in whatever Liquid files except for the layout Liquid files. Then don't endeavour to fix everything at once—option a battle and starting time there.
To make things a little easier, pick a page and start with the very first script you lot encounter after the opening trunk tag that is not in a layout Liquid file. Relax, information technology's like playing a game of Pokemon when yous offset enter a grassy area.
Outset encounter
You found your first enemy—I mean, script. Commencement, I want yous take out your measuring record and magnifying drinking glass and really sympathise what this script is doing.
Benchmark a script
We will be doing exactly what we did earlier with functioning marks, except now we will measure specifically for a given script, similar in the following case:
<script>
window.performance.mark(window.markNames.menuScriptParse.start);
<!-- Residue OF SCRIPT Code -->
window.performance.marker(window.markNames.menuScriptParse.end);
</script>
The above example will measure the parsing elapsing of this item script.Don't forget to add together new performance mark names in the theme.liquid
file:
In the panel log, we'll see something like this:

We can come across that the browser took most 12ms to parse. That doesn't seem too bad. The key is determining how many of these we have. If we have 200 of these scripts roaming around, that adds two seconds of duration.
Finding script dependencies
Earlier we tin can migrate the location of this script, we need to notice all its dependencies. These tin can be anywhere. Here are some clues to wait for:
-
$('css_selector')
JQuery. - Function calls to nowhere. Search where this part is declared.
-
{{ * }}
Liquid tags.
Document the dependencies at the beginning of the script. This will come up in handy when we start moving lawmaking effectually.
What to do when there are Liquid tags in the script
If the Liquid tag is a global tag, moving this slice of code to theme.liquid
will be fine. If the Liquid tag is associated with a particular template layout, wrap the script with the following:
{% if template == 'collection' %}
<script>
<!-- REST OF SCRIPT Code -->
</script>
{% endif %}
If the script code involves circuitous dependency on the existence of code somewhere, this is where you lot would showtime refactoring the lawmaking so that you can motion it out of the Liquid files.
Motility that code!
Once you've identified all the script dependencies, it'due south time to move the code. We're aiming to move all the code to the cease of the body tag. To maintain the original order of script execution(important in nearly cases, unless y'all figure out how to refactor any is in that location to be not social club dependent), go out information technology simply after the performance marker for torso cease scripts, like the following:
Progressively criterion your changes
After you've moved your code, make sure you didn't suspension the page by checking if what yous expected to happen, has happened.
parse_head showtime fourth dimension | Parse head | Parse_body layout | Parse_body end_scripts | First pigment | Room for improvement (ms) | |
Base of operations | 1090 | 2560 | 2107 | 17 | 4805 | 1155 |
Menu script | 946 | 2546 | 2046 | 24 | 4661 | 1169 |
Compared to the base measurements, nosotros tin see the parse elapsing for the torso layout has decreased and the parsing elapsing for the body terminate scripts has increased. Nosotros know the menu script has a 10ms parsing duration, so this is expected. The first pigment has decreased as well, just it is too early on to be conclusive of anything. We know that first paint can happen the moment the browser finishes parsing the head.
The Room for improvement column is the number of milliseconds of delay from the terminate of the parsing caput. It is a good indicator to tell usa if we are optimizing between a l percent proceeds versus a 1 percent proceeds.
Room for improvement = Kickoff paint — ( parse head start time + parse head duration )
Rinse and repeat
Now, practise the same thing for every script you come across in the centre of the body.
Parse caput start fourth dimension | Parse head | Parse body layout | Parse body terminate scripts | First paint | Room for improvement (ms) | |
Base of operations | 1090 | 2560 | 2107 | 17 | 4805 | 1155 |
Menu script | 946 | 2546 | 2046 | 24 | 4661 | 1169 |
Script 1 | 891 | 2569 | 2041 | 34 | 4622 | 1162 |
Script 2 | 928 | 2487 | 2039 | 78 | 4590 | 1175 |
Script 3 | 972 | 2540 | 2060 | lxxx | 4690 | 1178 |
Script four | 1022 | 3147 | 2080 | 118 | 5066 | 897 |
Script five 1 | 909 | 2561 | 1553 | 118 | 4716 | 1246 |
Script half dozen | 923 | 2561 | 1428 | 128 | 4734 | 1250 |
Script seven | 951 | 2557 | 1416 | 124 | 4746 | 1238 |
Script 8 | 921 | 2563 | 1325 | 152 | 4782 | 1298 |
Script 9 | 978 | 2556 | 1308 | 138 | 4825 | 1291 |
Script 10 2 | 1372 | 2568 | 1145 | 275 | 4052 | 112 |
This is truly a battle for the milliseconds. In the process of moving scripts to the bottom, some refactors were made so that the script in the middle of body is not dependent on the script's location. In the results higher up, we can see that nosotros have successfully reduced near ane 2d of the parsing duration for the body and shifted some of that parsing to the torso end scripts. This resulted in a relative 8 percent comeback for start pigment fourth dimension, which is near 320 ms.
5. The finishing move
Information technology'southward time for the last boss: moving all the scripts in the head to the end of the torso, while maintaining the script order.
Parse head get-go time | Parse head | Parse body layout | Parse torso stop scripts | First paint | Room for improvement (ms) | |
Base | 1090 | 2560 | 2107 | 17 | 4805 | 1155 |
All scripts | 977 | 1193 | 3938 | 161 | 2199 | 29 |
Let'due south understand what's happening here. Nosotros moved quite a few external script requests from the head tag to the body tag. External resources that were initially render blocking are no longer blocking. This allows the first pigment to happen much faster.


Nosotros have finer improved the start return time by most 40 percent, without losing any script functionalities. 🎉
You lot might too like: 4 Lesser Known but Powerful Web Programmer Tools that Increase Productivity.
6. Double bank check
Information technology never hurts to do this. We achieved amazing numbers simply by shifting script around the document. Give it a run through the web page examination. In my case, I found a very interesting problem.


The page had decent first pigment timing, but went dorsum to bare until the ten-second mark. What happened?
Turns out, the site implemented the anti-flicker snippet from Google Optimize'southward A/B experiment framework.
We have options to piece of work around this. We can try moving this Google Tag Manager script back to the top of the head and see how it does.

Honestly, I don't call back it's worth information technology. Information technology added three whole seconds to the first pigment, even if information technology'south the outset resource to download, just for the potential that there is an experiment to run. There are better ways to instrument A/B experiments without hiding the entire document for potentially four seconds, which is exactly what this anti-flicker snippet is doing.
This effect actually explained why I was not seeing progressive improvements as I moved the scripts out of the body. It was always delayed by this anti-flicker snippet.
Abound your business with the Shopify Partner Program
Whether you lot offer marketing, customization, or web design and development services, the Shopify Partner Plan will set you up for success. Join for free and access revenue share opportunities, tools to grow your business concern, and a passionate commerce community.
Sign up
Bring speed to your webpage
Success! We have improved start rendering fourth dimension, all without losing the scripts that we need to keep. Fixing site functioning is upward to all of us. As Shopify continues to improve site performance on the shop front, every programmer should practise what they tin to improve site performance as well. Information technology benefits everyone.
Boosted Resources
- Javascript Loading Priorities by Addy Osmani
- How Browsers Work by Tali Garsiel and Paul Irish
Source: https://www.shopify.co.id/partners/blog/javascript-performance
0 Response to "Shopify Failed to Run the Script; Refresh or Try Again Later"
Post a Comment