Skip to content

Instantly share code, notes, and snippets.

@thomedes thomedes/browser-x-load.js
Last active Aug 29, 2015

Embed
What would you like to do?
Load any file in the browser
///////////////////////////////////////////////////////////////////////////////
//
// browser_x_loader(tag_name, element_type, callbak[, end_callback])
//
// Load files in the browser
//
// Usage:
//
// <script type="text/x-toni-template" src="tmpl/default.tmpl"></script>
// <script type="text/x-toni-template" src="tmpl/login.tmpl"></script>
// <script type="text/x-toni-template" id="test-id">
// hello templates
// </script>
// <script src="js/browser-x-load.js"></script>
// <script>
// var templates = []
// function got_template(src, text) { templates[src] = text }
// function finished() { alert("Finished!") }
// browser_x_loader("script", "text/x-toni-template", got_template, finished)
// </script>
//
// Author: Toni Homedes i Saun (http://tonihomedes.cat/)
// License: CC-BY-SA
//
///////////////////////////////////////////////////////////////////////////////
function browser_x_loader(tag_name, element_type, callback, end_callback) {
"use strict"
var pending_elements
function assert(condition, message) {
if (!condition) {
throw "Assertion failed" + (message ? ": " + message : "")
}
}
function loadElement(src) {
var req = new XMLHttpRequest()
req.open('GET', src, true)
req.onreadystatechange = function (ev) {
if (
req.readyState == 4
&& (req.status == 200 || req.status == 0)
) {
send(src, req.responseText)
}
}
req.overrideMimeType(element_type)
req.send()
}
function addListener(elem, event, listener) {
assert(elem.addEventListener || elem.attachEvent,
"What am I supposed to do?")
if (elem.addEventListener) {
elem.addEventListener(event, listener, false)
} else if (elem.attachEvent) {
elem.attachEvent('on' + event, listener)
}
}
function discount1() {
assert(pending_elements > 0, "Something is very wrong...")
--pending_elements
if (pending_elements === 0 && end_callback) {
end_callback()
}
}
function send(src, text) {
callback(src, text)
discount1()
}
function on_load() {
var i, elements
elements = document.getElementsByTagName(tag_name)
pending_elements = 1 // Ghost element to prevent alerts before end
for (i = 0; i < elements.length; ++i) {
if (elements[i].getAttribute("type") === element_type) {
++pending_elements
if (typeof elements[i].src === 'string' && elements[i].src !== '') {
loadElement(elements[i].src)
} else {
send(elements[i].id, elements[i].text)
}
}
}
discount1() // Discount ghost
}
assert(window, "This does not seem to be a browser...")
addListener(window, "load", on_load)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.