Call JavaScript function after script is loaded
Quickly call a function the moment a dynamically loaded JavaScript script is ready by setting an onload
function on the created script tag:
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:
Tradition minus jQuery
For those who prefer doing things the plain way, sans jQuery, the onload
attribute is your time-tested subsequent function caller:
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:
For an even smoother finish, we’ve got the async
and await
elixir:
One-liner wonder for script loading
To make script loading simpler, like instant coffee, let's brew a loadScript
function:
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:
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.
Was this article helpful?