Last active
December 13, 2021 16:53
-
-
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 .
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
How to call that function and where do I specify what to inject?