Using jQuery in bookmarklets

Writing a javascript bookmarklet is a great way to add functionality to a web page that you don’t control. But if you use jQuery, wouldn’t it be neat to be able to use that in your bookmarklet? You can do this by loading jQuery in and adding it to the document:

var jQueryLib = document.createElement("script");
jQueryLib.src = "http://code.jquery.com/jquery-1.6.1.min.js";
document.body.appendChild(jQueryLib);

It may take the browser a second or two to load jQuery, so I’d recommend putting a delay in before your code continues. You can do this using the setTimeout function:

/* Give the browser a short while to load jQuery */
var myCode = setTimeout(function() {
  /* your code here */
  },1000);

The timeout is in milliseconds, so the above code puts in a one second delay before continuing execution.

This entry was posted in Javascript, jQuery and tagged , . Bookmark the permalink.

2 Responses to Using jQuery in bookmarklets

  1. Majid says:

    Good post, thanks for sharing. Anyway, this post proposes a better method than using setTimeout:
    http://coding.smashingmagazine.com/2010/05/23/make-your-own-bookmarklets-with-jquery/

Leave a Reply

Your email address will not be published. Required fields are marked *

503,793 Spambots Blocked by Simple Comments

HTML tags are not allowed.