Useful include function

From The WebGL Cookbook

Some times you wonder why is there not an easier way to import or include stuff...

Well here is a snippet that checks for file type and for multiple inclusion from different places in your code. And if its a go ads them to the head of the page so you dont need to cluter the body with lib or framework includes.

function include(url){
var element;
switch(url.split(".").pop()){
case "css":{
element=document.createElement("link");
element.setAttribute("rel","stylesheet");
element.setAttribute("type","text/css")
element.setAttribute("href",url)
}break;
case "js":{
element=document.createElement("script");
element.setAttribute("language","javascript")
element.setAttribute("src",url)
}break;
default:window.console && window.console.error("could not identify",url,"skip include");return;
}
var head=document.querySelector("head");
if(head.innerHTML.indexOf(element.outerHTML)!=-1){
window.console && window.console.warn("Duplicate include, skipping:",url);
}else{
head.appendChild(element);
}
}

Usage..

include("Hello World.css");
include("sylvester.js")
 
/*
* some code that depends on thes files
*/
TOOLBOX
LANGUAGES