Here is a little snippet for adding tags dynamically to your html file using JavaScript and DOM API.
// Add scripts to DOM by creating a script tag dynamically.
// @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
We use the native DOM API instead of jQuery for this particular case because of the way jQuery treats 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.