Skip to content

Instantly share code, notes, and snippets.

@datygra
Forked from nylen/inject.js
Created December 13, 2021 16:53
Show Gist options
  • Select an option

  • Save datygra/ca35eeca471ba8dfabb6bcb2627d9168 to your computer and use it in GitHub Desktop.

Select an option

Save datygra/ca35eeca471ba8dfabb6bcb2627d9168 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment