Explain Codes LogoExplain Codes Logo

Call JavaScript function after script is loaded

javascript
promises
callbacks
script-loading
Alex KataevbyAlex Kataev·Aug 26, 2024
TLDR

Quickly call a function the moment a dynamically loaded JavaScript script is ready by setting an onload function on the created script tag:

var script = document.createElement('script'); script.onload = function() { // It's showtime; call your function yourAwesomeFunction(); }; script.src = 'path_to_your_script.js'; // Keep your script path in check here document.head.appendChild(script);

This line-up calls yourAwesomeFunction the moment path_to_your_script.js loads to ensure seamless and immediate execution.

Crafting a cross-browser recipe

When concocting scripts dynamically, you can't forget about our old friends IE < 9. Keep them in the party using script.readyState and add an extra spice of error handling to the mix:

var script = document.createElement('script'); script.type = 'text/javascript'; // IE < 9 orders 'complete' not 'medium-rare' script.onreadystatechange = function() { if (this.readyState === 'complete' || this.readyState === 'loaded') { callback(); } }; script.onload = callback; script.onerror = function() { // Alert the chefs! We got burnt here console.error('Oops! Script slipped off the pan.'); }; script.src = 'path_to_your_script.js'; document.getElementsByTagName('head')[0].appendChild(script); // Call back the order when done function callback() { yourAwesomeFunction(); }

Tradition minus jQuery

For those who prefer doing things the plain way, sans jQuery, the onload attribute is your time-tested subsequent function caller:

<!-- A pure JS hammer time --> <script src="path_to_your_script.js" onload="yourAwesomeFunction()"></script>

Just like an old wine, this process is simple, effective, but needs to be used mindfully to prevent getting tipsy with tight-coupled logic.

Scripts and Promises: The modern affair

JavaScript has aged like a fine scotch, and Promises are its high notes. Here, we'll use those for an elegant, fruity script loading:

const loadScript = function (src) { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = src; // When the cake is baked (script loaded) script.onload = () => resolve(script); // Or the kitchen is on fire (loading error) script.onerror = () => reject(new Error(`💥 Bun in the oven alert! Couldn't load ${src}`)); document.head.appendChild(script); }); }; loadScript('path_to_your_script.js') .then(script => yourAwesomeFunction()) .catch(error => console.log(`🔥 Burn Notice: ${error.message}`));

For an even smoother finish, we’ve got the async and await elixir:

async function loadAndExecute(src) { try { await loadScript(src); yourAwesomeFunction(); } catch (error) { console.log(`🔥 Burn Notice: ${error.message}`); } } loadAndExecute('path_to_your_script.js');

One-liner wonder for script loading

To make script loading simpler, like instant coffee, let's brew a loadScript function:

function loadScript(src, callback) { const script = document.createElement('script'); script.src = src; // This is instant, not a filter coffee! script.onload = () => callback(); // If coffee machine breaks down script.onerror = () => console.error(`🔥 The script ${src} hasn't brewed properly.`); document.documentElement.appendChild(script); } loadScript('path_to_your_script.js', () => console.log('🚀 Lift off! Script has loaded.'));

This little dynamo loadScript is fast, efficient, and can be used all-around - like a handy Swiss Army knife.

The Swiss Army knives of script handling

From our loadScript function with integrated callback parameters to TypeScript for localizing global symbols, a plethora of tools are at your disposal:

// TypeScript version const loadScript = (src: string): Promise<void> => { return new Promise((resolve, reject) => { const script: HTMLScriptElement = document.createElement('script'); script.src = src; // When the stars align (the script loads) script.onload = () => resolve(); // Or when they don't (loading fails) script.onerror = () => reject(new Error(`No stellar alignment! Couldn't load the script: ${src}`)); document.head.appendChild(script); }); };

Going for performance? Techniques resembling JSONP for callbacks and placing the loadedContent() at the end of the dynamic script can speed up your scripts like a Falcon 9.

Applying the right tools for the right scripts

Picking methods based on practicality, evaluate scenarios where each of these strategies dazzle. Whether it's loadScript and callbacks for small gigs, or Promises when there's a trickier task at hand, it's all about using the right tool for the right script.