kubetail-org / loadjs

A tiny async loader / dependency manager for modern browsers (899 bytes)
MIT License
2.57k stars 149 forks source link

Add script type="module" support #84

Open asos-tomp opened 5 years ago

asos-tomp commented 5 years ago

https://developers.google.com/web/fundamentals/primers/modules

Accept args.module = true for a particular script to add type="module". It would be up to consumers to do a feature detect:

'noModule' in document.createElement('script')

...to decide which script to request in loadJs, but using the same identifier for both that and a traditional script.

amorey commented 5 years ago

You should be able to do this using the before callback:

loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
  success: function() {},
  error: function(pathsNotFound) {},
  before: function(path, scriptEl) {
    /* called for each script node before being embedded */
    if (path === '/path/to/foo.js') scriptEl.type = "module";
  }
});

Let me know if that helps.

asos-tomp commented 5 years ago

I hadn't considered that hook, thanks!

Would still be nice to have this embedded into the loader, however. I'm trying to keep the amount of code written to the page as small as possible, and the above is relatively verbose.

toddw commented 5 years ago

You can compress that down to something like:

before: function(p, l) { p == ‘/path’ && l.type= “module” }

If you are only targeting modern browsers you can make it even smaller:

before: (p, l) => p == ‘/path’ && l.type= “module”

In order to make that even smaller, it would probably require more code in loadjs. If you found a way somehow to make it smaller it’s probably not going to be super benefitial.

asos-tomp commented 5 years ago

Yep, makes sense. I guess I'm just thinking if you have a lot of scripts to load, and each needs to add the before: code, it might be nice to have a native option (like async), and hopefully only a very small addition to loadjs itself, i.e.

module = args.module
...
e.type = module ? "module" : undefined