YUI2: Dynamically add external javascript files
Simple YUI2 function for dynamically adding external javascript to the page after Dom ready.
I have written a simple function in YUI2 to dynamically add external javascript, for applications such as facebook and twitter, to my page once the Dom had loaded.
To add the javascript file to the head I get the first 'link' tag which is my CSS file:
existingTag = document.getElementsByTagName('link')[0];
I then wrote a small function to create a javascript tag and place it in the Dom after the link to the CSS file:
function createScriptTag(scriptURL) {
var scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = 'true';
scriptTag.src = scriptURL;
existingTag.parentNode.insertBefore(scriptTag, existingTag);
}
Once the Dom is ready I call the function and pass in the url of the external javascript file I wish to use:
createScriptTag('http://www.example.com/js/extranal-file.js');
In the full version of the code shown below I have two different versions of 'createScriptTag', the second one dynamically sets the 'http:' part of the url, this could be handy if some of your site runs in 'https:' and if the external source you are calling the javascipt from offers the files for both a secure and non-secure environment.
Requires the following YUI2 files:
- Dom
- Event
/*global document, YAHOO */
YAHOO.namespace('yourNamespaceHere');
YAHOO.yourNamespaceHere = (function () {
'use strict';
var init,
Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event,
existingTag = document.getElementsByTagName('link')[0];
function createScriptTag(scriptURL) {
var scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = 'true';
scriptTag.src = scriptURL;
existingTag.parentNode.insertBefore(scriptTag, existingTag);
}
init = function () {
var elementToCheck = Dom.get('elementToCheck');
if (elementToCheck) {
createScriptTag('http://www.example.com/js/extranal-file.js');
createScriptTag(document.location.protocol + '//www.example.com/js/extranal-file.js');
}
};
return {
init: init
};
}());
YAHOO.util.Event.onDOMReady(YAHOO.yourNamespaceHere.init);