Skip to content

Instantly share code, notes, and snippets.

@eouw0o83hf
Created March 27, 2015 06:33
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 eouw0o83hf/460d0d8fb37353a61b84 to your computer and use it in GitHub Desktop.
Save eouw0o83hf/460d0d8fb37353a61b84 to your computer and use it in GitHub Desktop.
Tampermonkey: Inject jQuery and Do Something With It
// Gets called when jQuery is all loaded and ready to go.
// Use jq instead of $ here. For instance,
// jq("div") or jq.get("targeturl");
function runWith(jq) {
// Do cool stuff here
}
// Get jquery, copied this from here http://blog.reybango.com/2010/09/02/how-to-easily-inject-jquery-into-any-web-page/
// with some minor modifications to do a callback whenever jQuery is either detected as having already
// been loaded or is done loading.
(function() {
var el=document.createElement('div'),
b=document.getElementsByTagName('body')[0];
otherlib=false,
msg='';
el.style.position='fixed';
el.style.height='32px';
el.style.width='220px';
el.style.marginLeft='-110px';
el.style.top='0';
el.style.left='50%';
el.style.padding='5px 10px';
el.style.zIndex = 1001;
el.style.fontSize='12px';
el.style.color='#222';
el.style.backgroundColor='#f99';
if(typeof jQuery!='undefined') {
msg='This page already using jQuery v'+jQuery.fn.jquery;
runWith(jq);
//return showMsg();
} else if (typeof $=='function') {
otherlib=true;
}
// more or less stolen form jquery core and adapted by paul irish
function getScript(url,success){
var script=document.createElement('script');
script.src=url;
var head=document.getElementsByTagName('head')[0],
done=false;
// Attach handlers for all browsers
script.onload=script.onreadystatechange = function(){
if ( !done && (!this.readyState
|| this.readyState == 'loaded'
|| this.readyState == 'complete') ) {
done=true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
getScript('http://code.jquery.com/jquery-latest.min.js',function() {
if (typeof jQuery=='undefined') {
msg='Sorry, but jQuery wasn\'t able to load';
} else {
runWith(jQuery);
msg='This page is now jQuerified with v' + jQuery.fn.jquery;
if (otherlib) {msg+=' and noConflict(). Use $jq(), not $().';}
}
return showMsg();
});
function showMsg() {
// Remove this return statement if you're having trouble getting jquery up and running
return;
el.innerHTML=msg;
b.appendChild(el);
bodyOfWork();
window.setTimeout(function() {
if (typeof jQuery=='undefined') {
b.removeChild(el);
} else {
jQuery(el).fadeOut('slow',function() {
jQuery(this).remove();
});
if (otherlib) {
$jq=jQuery.noConflict();
}
}
} ,2500);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment