Skip to content

Instantly share code, notes, and snippets.

@thurt
Last active December 18, 2015 19:10
Show Gist options
  • Save thurt/a85ffd895bee906d0f12 to your computer and use it in GitHub Desktop.
Save thurt/a85ffd895bee906d0f12 to your computer and use it in GitHub Desktop.
A non-blocking require function which dynamically loads javascript files synchronously into the DOM
function require(scripts, callback) {
var i, xhr, head, events = {
onload: function(e) {
var tag = document.createElement('script')
tag.textContent = xhr.responseText
head.appendChild(tag)
next()
},
onerror: function(e, message) {
console.error(`require script ${i+1} of ${scripts.length}:
"${scripts[i].id}" could not load. ${message||''}
require is ending prematurely.`)
end(false)
},
ontimeout: function(e) {
events.error(e, 'Operation timeout.')
}
}
function start() {
head = document.getElementsByTagName('head')[0]
if (!head) throw new ReferenceError('Missing <head> element')
i = -1; xhr = new XMLHttpRequest(); xhr.timeout = 5000
Object.assign(xhr, events)
next()
}
function next() {
if (!scripts[++i]) { return end(true) }
if (window[scripts[i].id]) { return next() }
// replace default event if a matching event is found on script
Object.keys(scripts[i]).forEach(key => {
(events[key]) ? xhr[key] = scripts[i][key] : xhr[key] = events[key]
})
xhr.open('GET', scripts[i].src, true)
xhr.send()
}
function end(is_success) {
if (is_success && callback) { callback() }
}
start()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment