Skip to content

Instantly share code, notes, and snippets.

Created November 22, 2013 14:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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 )
var newdom = document.createElement(tagname);
newdom[urlattr] = url;
if( type != "css" )
newdom.type = 'text/javascript';
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