Explain Codes LogoExplain Codes Logo

Dynamically load JS inside JS

javascript
async-await
error-handling
script-loading
Anton ShumikhinbyAnton ShumikhinยทSep 4, 2024
โšกTLDR

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:

function loadScript(url, callback) { var script = document.createElement('script'); script.src = url; // Let's party when the script loads ๐ŸŽ‰ script.onload = callback; document.head.appendChild(script); } // Utilization in action loadScript('script.js', () => console.log('The script has entered the building!'));

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 onerror handling.

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:

function loadScriptPromise(url) { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = url; // All clear for takeoff ๐Ÿš€ script.onload = resolve; // In case of turbulence ๐Ÿ˜ตโ€๐Ÿ’ซ script.onerror = reject; document.head.appendChild(script); }); } // Usage loadScriptPromise('another_script.js') .then(() => console.log('All systems go!')) .catch(error => console.error('Houston, we have a problem.', error));

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:

function loadFreshScript(url, callback) { const script = document.createElement('script'); // We're not above using cheap tactics ๐Ÿ˜‰ script.src = url + '?no_cache=' + new Date().getTime(); script.onload = callback; document.head.appendChild(script); } // Loading script with a force of freshness ๐Ÿ’ฆ loadFreshScript('script_to_reload.js', () => console.log('New and crunchy script served!'));

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.