Skip to content

Instantly share code, notes, and snippets.

@166MMX
Forked from sanemat/script.js
Last active October 11, 2015 10:27
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 166MMX/3845101 to your computer and use it in GitHub Desktop.
Save 166MMX/3845101 to your computer and use it in GitHub Desktop.
Script to load required external scripts before execution of user code - Cross browser compatible
// ==UserScript==
// @name CrossGrease
// @namespace https://gist.github.com/166MMX/
// @description Script to load required external scripts before execution of user code - Cross browser compatible
// @downloadURL https://gist.github.com/166MMX/3845101/raw
// @updateURL https://gist.github.com/166MMX/3845101/raw
// @version 1.3
// ==/UserScript==
var crossGrease = function () {
};
crossGrease.require = function (urls, onLoad, onError) {
var onFinishScope = {
'injected':urls.length,
'loaded':0,
'errors':0,
'onLoad':onLoad,
'onError':onError
};
var onFinish = function () {
this.loaded++;
if (this.injected === this.loaded) {
this.onLoad();
}
else if (this.injected === this.loaded + this.errors) {
this.onError();
}
};
var result = null;
if (urls instanceof Array) {
result = [];
for (var i = 0, l = urls.length; l > i; i++) {
result.push(crossGrease.inject(urls[i], function () {
onFinish.call(onFinishScope);
}, function () {
onFinish.call(onFinishScope);
}));
}
}
else if ('string' === typeof urls) {
result = crossGrease.inject(urls, onLoad, onError);
}
return result;
};
crossGrease.inject = function (url, onLoad, onError) {
var dScript = null;
if ('string' === typeof url) {
dScript = document.createElement("script");
dScript.setAttribute("src", url);
if ('function' === typeof onLoad) {
dScript.addEventListener("load", onLoad);
}
if ('function' === typeof onError) {
dScript.addEventListener("error", onError);
}
document.body.appendChild(dScript);
}
return dScript;
};
crossGrease.execute = function (functionOrCode) {
var scriptText = null, dScript = null;
switch (typeof functionOrCode) {
case 'function':
scriptText = '(' + functionOrCode + ')();';
break;
case 'string':
scriptText = functionOrCode;
break;
default:
break;
}
if ('string' === typeof scriptText) {
dScript = document.createElement("script");
dScript.textContent = scriptText;
document.body.appendChild(dScript);
}
return dScript;
};
crossGrease.requireAndExecute = function (urls, functionOrCode) {
crossGrease.require(urls, function () {
crossGrease.execute(functionOrCode);
});
};
crossGrease.requireJQuery = function (version, functionOrCode) {
if ('function' === jQuery && 'object' === jQuery.fn && 'string' === typeof jQuery.fn.jquery) {
crossGrease.execute(functionOrCode);
}
else {
var url = '//ajax.googleapis.com/ajax/libs/jquery/' + version + '/jquery.min.js';
crossGrease.requireAndExecute(url, functionOrCode);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment