How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.
The client that uses the component isn't required to load all the library script files (and manually insert <script>
tags into their web page) that implement this component - just the 'main' component script file.
How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)? Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file? Or do they do any dynamic loading of ancillary 'library' scripts?
An addition to this question: is there a way to handle the event after a dynamically included JavaScript file is loaded? Prototype has document.observe
for document-wide events. Example:
document.observe("dom:loaded", function() {
// initially hide all containers for tab content
$$('div.tabcontent').invoke('hide');
});
What are the available events for a script element?
Here is a simple one with callback and IE support:
I think just adding the script to the body would be easier then adding it to the last node on the page. How about this:
Here a simple example for a function to load JS files. Relevant points:
$.ajax
or$.getScript
you can use nonces, solving thus issues with CSPunsafe-inline
. Just use the propertyscript.nonce
Now you use it simply by
An absurd one-liner, for those who think that loading a js library shouldn't take more than one line of code :P
Obviously if the script you want to import is a module, you can use the
import(...)
function.Keep it nice, short, simple, and maintainable! :]
This code is simply a short functional example that could require additional feature functionality for full support on any (or given) platform.
There's a new proposed ECMA standard called dynamic import, recently incorporated into Chrome and Safari.