// Add scripts to DOM by creating a script tag dynamically.We use the native DOM API instead of jQuery for this particular case because of the way jQuery treats <script> tags. jQuery inserts script to DOM, then evaluates the script separately and then it removes the tag from the DOM. So you won't see the script tag, but the script will get executed.
// @param {String=} url Url of a js file
// @param {String=} src Script source code to add the source directly.
// NB: At least one of the parameters must be specified.
var hookScripts = function(url, src) {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = url || null;
s.innerHTML = src || null;
document.getElementsByTagName("head")[0].appendChild(s);
};
// usage eg:
hookScripts('url/path/to/myscript.js'); //url
hookScripts(null, 'alert("hello");'); //giving the source code directly
Tuesday, January 3, 2012
Add script tags to DOM dynamically using javascript
Here is a little snippet for adding <script> tags dynamically to your html file using javascript and DOM api.