Created
January 9, 2015 14:03
-
-
Save mkrogh/0de19b08a4212c1f8c35 to your computer and use it in GitHub Desktop.
A simple js include
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
"js/util/dom-creator.js", | |
"js/main.js" | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Usage: | |
* <script data-modules='modules.json' src='js/simple-modules.js' type='text/javascript'></script> | |
* Will load all js files specified in modules.json array: | |
* | |
*/ | |
(function(){ | |
var $src = document.querySelector("script[data-modules]"); | |
var mods = $src.dataset["modules"].split(","); | |
·· | |
var url; | |
for(var i=0; i < mods.length; i++) { | |
url = mods[i].trim(); | |
if(url.indexOf(".json") !== -1){ | |
load_json(url); | |
}else{ | |
load_js(url); | |
} | |
} | |
function load_js(url) { | |
var script = document.createElement("script"); | |
script.type ="text/javascript" | |
script.src = url; | |
$src.parentElement.appendChild(script) | |
} | |
function load_json(url) { | |
var handleJSON = function handleJSON(data){ | |
for(var i=0; i < data.length; i++){ | |
load_js(data[i]); | |
} | |
} | |
getJSON(url, handleJSON); | |
} | |
//From: https://mathiasbynens.be/notes/xhr-responsetype-json | |
function getJSON(url, successHandler, errorHandler) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open('get', url, true); | |
xhr.responseType = 'json'; | |
xhr.onload = function() { | |
var status = xhr.status; | |
if (status == 200) { | |
successHandler && successHandler(xhr.response); | |
} else { | |
errorHandler && errorHandler(status); | |
} | |
}; | |
xhr.send(); | |
};· | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment