Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

Re: Check if a script is loaded

Check if a script is loaded

RiccardoPavesi
Shopify Partner
5 0 5

Hi,

I'm loading an asset js requesting it on a section, but I would like to be loaded only in the first instance of the section and not every time the section is rendered. I can't load it outside because of performance issues.

Is there any way to check if a script is been loaded before in liquid?

Thanks

Replies 2 (2)

eballeste1
Excursionist
23 4 17

The best way to guarantee that this loads a single time would be to load it in the global `layout/theme.liquid` file where it will only be loaded once. If performance is an issue, your best bet would be to async or defer the loading of the asset so browsers know to load it when necessary. 

Take a look at the examples of how shopify recommends you load your javascript assets:
https://github.com/Shopify/theme-check/blob/main/docs/checks/parser_blocking_javascript.md

nandumoura
Tourist
5 1 2

I believe that for this request you would have to create a variable in theme.liquid or on the specific page where you will render this script more than once as follows

{% assign myScriptIsLoaded = false %}

and in this section some like this

{% unless myScriptIsLoaded %}
<script src="someurl">
{% myScriptIsLoaded = true %}
{% endunless %}

but I sincerely believe that this way the performance tends to be worse than adding directly to the theme.liquid

with the defer attribute because you end up doing validations on the shopify backend which is in ruby and does not have a very interesting performance