I have seen Scriptaculous.js file to include its required javascript files dynamically. Is there any better approach to include javascript dynamically.
For example,
I've seen what the scriptaculous loader does. What it does is that it goes through all script tags in the document to find the one that loaded itself, e.g:
Then it parses the querystring used inside the src attribute and dynamically create additional script tags for each script file. At the same time it also parses the path of the base script (/path/to/single.js
) and uses the same path to load dependency files (e.g. /path/to/first.js
).
You can create your own script loader like this. In vanilla javascript, you can use the following functions:
Anand Thangappan has posted a solution that uses these functions. If you're using a framework such as jQuery or MooTools then both provide their own implementations of dynamically loading JsvaScript.
Finally, there is a server side solution for your problem. Look at minify -- Combines and minifies multiple CSS or JavaScript files into a single download.