Is there a way to use dynamic imports to load into the browser Javascript libraries made available over CDN, like jQuery e.g.:
> import('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.js')
.then(console.log)
.catch(console.error)
Rather than making jQuery available, the above produces the rather obscure:
It feels like this absurdly simple example, essentially following the MDN documentation, should do something other than this, and in particular the script should be downloaded, parsed, and made available as the fulfillment of the promise.
The Network panel of DevTools
indicates that the file itself was correctly downloaded, with a content-type of content-type: application/javascript
, however there is no indication that the content was interpreted, and if it's made available it's not obvious how to access it.
import()
returns a Promise
with all the considerations that a Promise
entails. In this case, jQuery will be available globally, due to how jQuery initializes itself, but not until the Promise
resolves. Keep in mind that, while the Promise
is waiting to resolve, code elsewhere is free to run but jQuery may not be available just yet.
For example:
import('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.js')
.then(() => {
jQuery('<div>Hello, World!</div>').appendTo('body');
});
Or:
(async () => {
await import('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.js');
jQuery('<div>Hello, World!</div>').appendTo('body');
})();
But this is problematic:
<script>
(async () => {
await import('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.js');
jQuery('<div>Hello, World!</div>').appendTo('body');
})();
</script>
<script>
// jQuery usually won't be available here, so we get an exception
jQuery('<div>First?</div>').appendTo('body');
</script>
And this can be a problem, too:
import('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.js')
.then(() => {
jQuery('<div>Hello, World!</div>').appendTo('body');
});
// No jQuery here, import hasn't resolved
jQuery('<div>First?</div>').appendTo('body');