Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple way to include a css or js on the fly only once.
/**
* to includes script/css files only if there are not loaded yet.
*
* @param url url of the resource
* @param type js or css (empty default is js)
*/
function include_once(url,type)
{
var tagname;
var urlattr;
if( type != "css")
{
tagname = "script";
urlattr = "src";
} else {
tagname = "link";
urlattr = "href";
}
var domelements = document.getElementsByTagName(tagname);
// if the url is relative the dom element contains the absolute url after injection
// so we check only if the urls end the same way
if( domelements )
for( var i=0; i<domelements.length; i++ )
if( domelements[i][urlattr].match(url+"$") == url )
return;
var newdom = document.createElement(tagname);
newdom[urlattr] = url;
if( type != "css" )
newdom.type = 'text/javascript';
else
newdom.rel = 'stylesheet';
// add to head or body
(document.getElementsByTagName('head')[0] || document.body).appendChild(newdom);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment