Skip to content

Instantly share code, notes, and snippets.

@ymatuhin
Last active January 14, 2016 20:52
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 ymatuhin/09825794154dc453c2a5 to your computer and use it in GitHub Desktop.
Save ymatuhin/09825794154dc453c2a5 to your computer and use it in GitHub Desktop.
var loadFile = (function () {
var links = document.getElementsByTagName('link');
var scripts = document.getElementsByTagName('script');
var head = document.getElementsByTagName('head')[0];
var need = {
css: true,
js: true
}
function isNeed(url, ext) {
need[ext] = true;
var arr = (ext == 'js') ? scripts : links;
for (var i = 0; i < arr.length; i++) {
if (arr[i].href == url) need[ext] = false;
}
return need[ext];
}
return function (url, cb) {
var ext = url.slice(url.lastIndexOf('.') + 1);
if (!ext || !isNeed(url, ext)) return;
var el = document.createElement(ext == 'css' ? 'link' : 'script');
if (cb) { el.onload = cb; }
if (ext == 'css') el.rel = "stylesheet";
if (ext == 'css') el.href = url;
if (ext == 'js') el.src = url;
if (ext == 'js') el.async = true;
head.appendChild(el);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment