Run Inline script after External script has loaded
by Nicklas EnvallSometimes you want to (or are forced to) run an inline script after you load an external script.
So how do you do that?
The naïve approach would be render-blocking:
<script src="functionA.js"></script> <script> functionA(); </script>
The solution is to listen to the load
event that's fired when the script has been fetched. To do that, we can add the onload
event attribute directly on the script, on which we invoke our functionA
function:
<script src="functionA.js" onload="functionA();"></script>
Also, let's not forget that we can add either defer
or async
to tell the browser to continue constructing the DOM while fetching the script.
<script defer src="functionA.js" onload="functionA();"></script>
Need a JavaScript solution instead? Well, that's possible as well:
var script = document.createElement("script"); script.type = "text/javascript"; script.onload = function () { console.log('script loaded'); }; script.src = "functionA.js"; script.async = true; document.getElementsByTagName("head")[0].appendChild(script);
Lastly, I would like to point out that when doing window.onload
or window.addEventListener('load', ...)
we are waiting until the page has loaded - not the actual script.