Dynamically load JS inside JS
The following snippet shows how to dynamically load an external JS file within your JavaScript code. Here, a script element is created, its src is set, and it's finally added to the document:
The callback function acts as a party planner, holding onto the main event until the newly loaded script can join in.
Managing script dependencies
Often, it's not enough to just slap scripts onto the document. Sometimes, scripts are like melodramatic actors: they insist on arriving in a specific order. Here's what we can do to cater to their whims:
- Sequential Loading: Ensure dependent scripts enter the stage in the correct order.
- Parallel Loading: Load independent scripts in tandem to beat the load time blues.
- Error Handling: Brace for impact when a script fails to load with suitable
onerrorhandling.
Promises for cleaner syntax
JavaScript Promises are like your always-organized friend who makes handling asynchronous tasks a breeze. Let's see this friend in action while dynamically loading a script:
This technique provides you with top-notch error handling and easy integration with async/await syntax.
Rat race against caching
In this region of the internet, browsers love their cache. To beat browsers at their caching game when loading updated scripts, here's a cheeky trick:
By appending unique time-stamps (or a unique token) as a query parameter, you ensure a fresh-hot copy is served up!
Making everyone feel included
- Browser Support: Keep your script loading welcoming to all the guests, by supporting IE8+ browsers.
- TypeScript: For more maintainable, and type-safe script loading functions, consider cordially inviting TypeScript to your coding party.
Was this article helpful?