Skip to content

Instantly share code, notes, and snippets.

@adrienjoly
Created February 14, 2012 13:20
Show Gist options
  • Save adrienjoly/1826721 to your computer and use it in GitHub Desktop.
Save adrienjoly/1826721 to your computer and use it in GitHub Desktop.
native code to include a javascript / css file dynamically in a html document
function include(src, callback) {
var ext = src.split(/[\#\?]/)[0].split(".").pop().toLowerCase();
var inc;
if (ext == "js") {
inc = document.createElement("script");
inc.src = src;
inc.onload = inc.onreadystatechange = callback;
}
else {
inc = document.createElement("link");
inc.rel = "stylesheet";
inc.type = "text/css";
inc.media = "screen";
inc.href = src;
if (callback)
callback ();
}
document.getElementsByTagName("head")[0].appendChild(inc);
};
// example of use 1/2: load a CSS and a JS file in the same time
include("http://mysite.com/bookmarklet.css");
include("http://mysite.com/bookmarklet.js");
// example of use 2/2: loading a list of JS and CSS files sequentially
var toInclude = [
"bookmarklet.css",
"bookmarklet.js"
];
(function loadNext(){
if (toInclude.length)
include("http://mysite.com/" + toInclude.shift(), loadNext);
else
console.log("everything is loaded!"); // your code here
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment