Rey Bango

JavaScript, HTML, CSS & Random Stuff…

How to Easily Inject jQuery into any Web Page

I use jQuery…a lot. It just makes JavaScript development much easier for me. Every so often, I may come across a site where I want to poke around and see what’s going on under the hood. In many cases, jQuery is being used so it’s simple to spark up Firebug and leverage jQuery to work with a document. While jQuery is very pervasive, there are still plenty of sites that don’t use it which forces me to go back to plain ‘ole JavaScript. There’s nothing wrong with that but I’ve gotten used to the nice, terse syntax jQuery provides and I’d like to be able to use it.

Awhile back, I came across an awesome bookmarklet created by my jQuery teammate, Karl Swedberg, which allows me to inject the latest version of jQuery right into my page. This is great when you want to work with a page which doesn’t have jQuery included and you either don’t own the page or don’t feel like adding a script tag to it. The code below shows how the jQuery lib is included.

It’s fairly straightforward in that a script element is created:

var script=document.createElement('script');

and the script tag’s src attribute is set with the following URL:

‘http://code.jquery.com/jquery-latest.min.js’

Then, they grab a reference to the document’s head DOM element:

var head=document.getElementsByTagName('head')[0]...;

and then insert the new script tag into the head of the document.

head.appendChild(script);

That was a very high-level explanation because there’s definitely more going on. In fact, Karl took the extra step of ensuring that jQuery’s .noConflict() method is called should there be another library present that requires the “$” namespace. Very cool. :)

Now, this leverages the latest minified version from the jQuery repo but you should be able to easily include a version of jQuery from the Microsoft or Google CDNs if that’s your preference:

Microsoft: http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js
Google: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

You can find the full source for the bookmarklet below and if you want to install it now, here’s the link for you to use:

» jQuerify «– Drag this link to your browser toolbar

I created a quick screencast that shows you how to add the bookmarklet to your browser and then use it for playing with a web page:

Nicely formatted bookmarklet code:

(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;
 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 {
   msg='This page is now jQuerified with v' + jQuery.fn.jquery;
   if (otherlib) {msg+=' and noConflict(). Use $jq(), not $().';}
 }
 return showMsg();
  });
  function showMsg() {
 el.innerHTML=msg;
 b.appendChild(el);
 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);
  }
})();

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Category: jQuery

Tagged:

12 Responses

  1. Very nice! Added this as a bookmark!

  2. You know, if you want to modify people’s pages and what not, you should use Kynetx (http://www.kynetx.com/). It is an evented way of programming the internet! Feel free to ping me on Twitter (@JessieAMorris) or via Email with questions!

  3. Steve Hebert says:

    Check out the jsshell extension for Chrome, the same pattern here is used for a great dev tool. I wish this was available for IE9 as well:

    http://somewebguy.wordpress.com/2010/01/12/jsshell-2-0-the-release/

  4. Bouke says:

    You should really change “This page already using jQuery” to “This page is already using jQuery”, it sounds very stupid :P

  5. JGarrido says:

    If you’re using FireFox and have FireBug installed (which of course, you do), FireQuery is a great extension that handles jQuery injections, among other incredibly awesome things: http://firequery.binaryage.com/

  6. Roger Pence says:

    Frickin awesome. This is superb teaching aid for jQuery! Thank you.

  7. avmusa says:

    Excellent!

  8. How to Easily Inject jQuery into any Web Page – Rey Bango…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  9. Ruman says:

    you saved my day :) .. Keep doing the good work

  10. Kirjava says:

    It doesn’t work for me on Chrome :
    Jquery wasn’t able to load

Leave a Reply

Learn JavaScript!

What to Read to Get Up to Speed in JavaScript.

The best books & blogs for learning JavaScript development. Broken down by experience levels!


My BIG LIST of JavaScript, CSS & HTML Development Tools, Libraries, Projects, and Books.

Constantly updated with the latest and greatest tools. Check it out!

Contact Me

GMail: reybango at gmail dot com
Twitter: @reybango

Haters gonna hate: What's that you said, Cobra?






JavaScript JS Documentation: JS Function Example: Specifying arguments with the Function constructor, JavaScript Function Example: Specifying arguments with the Function constructor

Twitter

Rey Bango is Stephen Fry proof thanks to caching by WP Super Cache