walmartlabs / little-loader

A lightweight, IE8+ JavaScript loader
MIT License
370 stars 28 forks source link

Add a way to set "defer" on the <script /> #54

Closed rubenspgcavalcante closed 6 years ago

rubenspgcavalcante commented 6 years ago

Hello, First, thanks for the awesome library! I was looking thru the docs and didn't found a way to add it to the injected script. I'm trying to use it for the google recaptcha, which need both async and defer on the script tag: https://developers.google.com/recaptcha/docs/display#explicit_render

ryan-roemer commented 6 years ago

Hi @rubenspgcavalcante -- We expose a setup(script) function that can arbitrarily mutate the script object before insertion. See https://github.com/walmartlabs/little-loader#calling

Offhand, you should be able to do something like:

// Load, call `setup(script)` on the script tag before insertion, no callback
load("http://foo.com/foo.js", {
  setup: (script) => {
    script.defer = true; // mutate to add defer.
  },
  callback: () => { // optional
    console.log("LOADED!"); 
  }
});

I think something like that should work for you (might need to experiment -- note that there are other options like context too if you need it).

rubenspgcavalcante commented 6 years ago

Ah got it :) In the docs wasn't so clear that the callback had the HTMLScriptElement as argument. I though that was the extracted module as the ES2015 dynamic import does. Maybe I can help and add it to the docs, if isn't a problem :)