Skip to content

Instantly share code, notes, and snippets.

@nylen
Last active December 13, 2021 16:53
Show Gist options
  • Save nylen/6234717 to your computer and use it in GitHub Desktop.
Save nylen/6234717 to your computer and use it in GitHub Desktop.
JavaScript file to allow injecting scripts into a page using GreaseMonkey/TamperMonkey and running a callback when loading is complete. Based on http://stackoverflow.com/questions/6725272/dynamic-cross-browser-script-loading .
function inject(src, callback) {
if (typeof callback != 'function') callback = function() { };
var el;
if (typeof src != 'function' && /\.css[^\.]*$/.test(src)) {
el = document.createElement('link');
el.type = 'text/css';
el.rel = 'stylesheet';
el.href = src;
} else {
el = document.createElement('script');
el.type = 'text/javascript';
}
el.class = 'injected';
if (typeof src == 'function') {
el.appendChild(document.createTextNode('(' + src + ')();'));
callback();
} else {
el.src = src;
el.async = false;
el.onreadystatechange = el.onload = function() {
var state = el.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
}
var head = document.head || document.getElementsByTagName('head')[0];
head.insertBefore(el, head.lastChild);
}
@PBonski
Copy link

PBonski commented May 13, 2015

How to call that function and where do I specify what to inject?

@nmaxcom
Copy link

nmaxcom commented Jun 7, 2015

@PBonski commented on May 13, 2015, 1:39 PM GMT+2:

How to call that function and where do I specify what to inject?

AFAIK just write a function for ex:

function pbonski(){
    doYourStuff();
    var here = 1;
}

and then:

inject(pbonski, callback);

Callback function is not mandatory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment