Skip to content

Instantly share code, notes, and snippets.

@imyelo
Last active August 29, 2015 13:58
Show Gist options
  • Save imyelo/10338716 to your computer and use it in GitHub Desktop.
Save imyelo/10338716 to your computer and use it in GitHub Desktop.
wrap or leak, sync or async
;(function () {
var loadScript = (function () {
var debug = typeof debug !== 'function' ? function (text) {
console.log(text);
} : debug;
var wrapAsync = function (url, doc, win) {
debug('load script: (safe and async) ' + url);
$.ajax({
url: url,
dataType: 'text',
success: function (result) {
var func;
func = new Function('document', 'window', result);
func(doc, win);
}
});
};
var wrapSync = function (url, doc, win) {
debug('load script: (safe and sync) ' + url);
$.ajax({
url: url,
dataType: 'text',
success: function (result) {
var func;
func = new Function('document', 'window', result);
func(doc, win);
},
async: false
});
};
var leakAsync = function (url) {
debug('load script: (leak and async) ' + url);
script = document.createElement('script');
script.src = url;
document.getElementsByTagName('body')[0].appendChild(script);
};
var leakSync = function (url) {
debug('load script: (leak and sync) ' + url);
document.write('<script src="' + url + '"><\/script>');
};
var load = function (url, options) {
var defaults = {
win: {},
doc: {},
sync: false
};
var isWrap, isSync, win, doc;
options = typeof options === 'undefined' ? {} : options;
isWrap = typeof options.win !== 'undefined' || typeof options.doc !== 'undefined';
isSync = typeof options.sync === 'undefined' ? defaults.sync : options.sync;
if (isWrap) {
win = typeof options.win === 'undefined' ? defaults.win : options.win;
doc = typeof options.doc === 'undefined' ? defaults.doc : options.doc;
}
if (isWrap && isSync) {
return wrapSync(url, doc, win);
}
if (isWrap && !isSync) {
return wrapAsync(url, doc, win);
}
if (!isWrap && isSync) {
return leakSync(url);
}
if (!isWrap && !isSync) {
return leakAsync(url);
}
};
return load;
})();
window['loadScript'] = loadScript;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment