Skip to content

Instantly share code, notes, and snippets.

@mikeyledoux
Last active December 5, 2017 21:31
Show Gist options
  • Save mikeyledoux/4643004 to your computer and use it in GitHub Desktop.
Save mikeyledoux/4643004 to your computer and use it in GitHub Desktop.
HTML5 Boilerplate-friendly CORE JS Lib Loader: An improvement on my 'jQuery Lib Loader'. It doesn't rely on jQuery. It can pull in assets at will and be used anywhere in the body.
var Ajax = function (url, callback, where) {
"use strict";
var _this = this;
_this.httpRequest = false;
_this.callback = callback;
_this.where = where;
_this.url = url;
_this.init();
};
Ajax.prototype = {
init: function () {
"use strict";
//console.log('initiated');
var _this = this;
if (window.XMLHttpRequest) {
_this.httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
_this.httpRequest = new window.ActiveXObject("Microsoft.XMLHTTP");
}
_this.resp();
},
resp: function () {
"use strict";
var _this = this;
_this.httpRequest.onreadystatechange = function () {
if (_this.httpRequest.readyState === 4) {
if (_this.httpRequest.status === 200) {
var testJSON = _this.httpRequest.response.indexOf("{") === 0;
if (testJSON) {
new _this.JSONCallback(_this.httpRequest.response);
} else {
var script = document.createElement("script");
script.src = _this.url;
document.getElementsByTagName("head")[0].appendChild(script);
if (_this.callback) {
_this.callback();
}
}
} else {
alert("There was a problem with the request.");
}
//Remove the above alert, as it's only for testing purposes.
}
};
},
JSONCallback: function (data) {
"use strict";
var _this = this;
//console.log("JSON detected...");
//Remove the console call for browser compatibility, if using in a production environment.
if (_this.callback) {
_this.callback(data);
}
},
call: function () {
"use strict";
var _this = this;
_this.httpRequest.open("GET", _this.url, true);
_this.httpRequest.send(null);
}
};
var libLoader = {};
libLoader.init = function (lib_type, callback) {
"use strict";
function renderScript() {
var ajaxy = new Ajax(lib_type, callback);
ajaxy.call();
}
if (lib_type !== "undefined") {
renderScript();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment