Created
November 19, 2016 22:37
-
-
Save ka7eh/c61f94e4da0e673f6a4277b720158d28 to your computer and use it in GitHub Desktop.
Dynamic loading of js and css dependencies in DOM
This file contains hidden or 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
function loadDependencies(deps, callback) { | |
var dep = deps.shift(); | |
if (dep['script'] && typeof(window[dep['lib']]) != dep['loadType'] || 'function') { | |
var depScript = document.createElement('script'); | |
depScript.type = 'text/javascript'; | |
depScript.src = dep['script']; | |
(document.getElementsByTagName('head')[0]).appendChild(depScript); | |
} | |
if (dep['css']) { | |
var depCSS = document.createElement('link'); | |
depCSS.rel = 'stylesheet'; | |
depCSS.href = dep['css']; | |
(document.getElementsByTagName('head')[0]).appendChild(depCSS); | |
} | |
if (!deps.length && typeof(callback) != 'undefined') { | |
if (depScript) { | |
depScript.onload = callback; | |
} else { | |
callback(); | |
} | |
} | |
if (deps.length > 0) { | |
if (depScript) { | |
depScript.onload = function () { | |
loadDependencies(deps, callback); | |
}; | |
} else { | |
loadDependencies(deps, callback); | |
} | |
} | |
} | |
// How to use: | |
var dependencies = [ | |
{ | |
lib: 'Handlebars', | |
script: 'static/deps/handlebarsjs/handlebars.min.js', | |
loadType: 'object' | |
}, { | |
css: 'static/deps/base.css' | |
} | |
]; | |
loadDependencies(dependencies, function () { | |
for (var i in options.templateHelpers) { | |
Handlebars.registerHelper(i, options.templateHelpers[i]); | |
} | |
template = Handlebars.compile(options['preview_template']); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment