A space to discuss online store customization, theme development, and Liquid templating.
I'd like to use the script_tag filter to load a script.
Example:
{{ 'section-mattress-layers.js' | asset_url | script_tag }}
However, I need to defer the script. Is there a Liquid option to do this? Or am I forced to use the following approach?
<script src="{{ 'global.js' | asset_url }}" defer="defer"></script>
I want this too (namely for adding crossorigin) but it seems like the filters don't support any additional options.
I had a look at the Shopify filter code on GitHub and the only parameter that this filter takes and outputs is a URL.
What you suggested above with the manually written <script> block and adding the script's src with the asset_url filter seems to be the only want to add additional attributes to the script block.
Actually I was also looking for the same but this feature is not yet added by Shopify.
You can use this as you mentioned:
<script src="{{ 'global.js' | asset_url }}" defer></script>
'script_tag' outputs the <script src="myurl"> and </script> tags which you don't need since you already added them to the code. Myurl is the output of the URL of global.js in the assets folder. So, the output will be: <script src="https://mywebsite.com/myassetsfolder/global.js" defer></script>