Skip to content

Instantly share code, notes, and snippets.

@HerbertV
Created November 22, 2013 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HerbertV/7600546 to your computer and use it in GitHub Desktop.
Save HerbertV/7600546 to your computer and use it in GitHub Desktop.
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