Scripttag : how to load defer

Highlighted
Tourist
12 0 2

I used scripttag to insert a js resource into storefront pages. The script tag is added to the page with "async" attribute. My question : Is it possible to load the scripttag with "defer" instead of "async"?

I dont see anything about this mentioned in the api page https://help.shopify.com/en/api/reference/online-store/scripttag

0 Likes
Shopify Staff
Shopify Staff
619 48 91

 

Hi @globalizeit,

 

The only option currently is Async, though it's something we've wanted to explore for a while now. Loading script tags with defer is not possible as it stands.

0 Likes
Highlighted
Shopify Partner
1 0 1

It's actually possible.

 

The approach relies on creating two methods which:

 

1. generate asset urls in javascript (`assetUrlFor`)

2. load a script tag with the defer attribute set to true (`loadScriptDeferredFor`)

 

As a bonus, I've set it up so that you can execute arbitrary code after the script is loaded.

 

If you have any more questions feel free to reach out ! lee@luchtimelabs.io

 

 

/** Code Snippet by Lunchtime Labs (lee@lunchtimelabs.io) **/

/* Begin: do not alter */
  var assetTemplate = "{{ '[ASSET_NAME]' | asset_url }}"

  function assetUrlFor(assetName) {
    return assetTemplate.replace(
      "[ASSET_NAME]",
      assetName
    )
  }

    function loadScriptDeferred(url) {
      return new Promise(function(resolve) {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src=url;
        script.defer = true;
        script.onload = resolve();
        head.appendChild(script);
      });
    }
/* End: do not alter */

loadScriptDeferred(assetUrlFor('[ENTER_YOUR_FILE_NAME].js')).then(function() {
  // code executed after load
});

 

 

 

1 Like