I usually only post How-to’s after I find a way to do something that has been vexing me for a while. This is another one of those tutorials.
The problem I ran into was I wanted to make it so I only have to give them one line of code, and so it would run automatically without any click or action on their part. Essentially, I needed one script that would both load the other scripts and run them automatically once everything was ready.
For example, let’s say we want to load jQuery and then use it to show a hidden element. To do this normally we would use:
Of course this means we have to add more than one line of code. What I wanted was more along the lines of:
Except in a single block of script.
Dynamically load multiple external scripts and then run them once everything is ready, without onload, onclick, or another unwanted method after the page loads.
My solution is to call the above line of script which contains:
for(src in scripts)
Or the minified version:
What this does is add three new script elements to the document while the page loads, each able to call functions declared in those before it because it’s inside a seperate <script> block.
This solution has been tested in various versions of Firefox, Opera, and Internet Explorer, and has been updated to work with Chrome and Safari as well.
My older version which relied on document.createElement occasionally failed in Webkit because the browser continued to run embedded scripts before those dynamically added in DOM. This update should work better.