Write Your Own JavaScript Bookmarklet

Bookmarklets are hard to write. You've got to strip line endings, extra whitespace, and encode characters. Once you've done that the resulting script is hard to read and modify. But, there is an easier way.

I wrote the bookmarklet below to dynamically load a JavaScript file from anywhere on the web. This way, the JS code is written in the normal way, stored on a web server somewhere, and loaded dynamically by a bookmark containing the following code. An added benefit is that anyone who is using the bookmarklet automatically gets your latest changes.

javascript:(function(){function bmLoader(jsFile) { var head = document.getElementsByTagName('head')[0]; var fileref = document.createElement('script'); fileref.type = 'text/javascript'; fileref.src = jsFile; head.appendChild(fileref); } bmLoader('http://www.joeldare.com/bm/example.js');})()

To use this code yourself, simply replace 'http://www.joeldare.com/bm/example.js' with the full URL to your own JS file.

Because the bookmarklet code is compressed into a single line, it's a bit difficult to read. The full version, before I compressed it into a usable bookmarklet, is below.

function bmLoader(jsFile) {
  var head = document.getElementsByTagName('head')[0];
  var fileref = document.createElement('script');
  fileref.type = 'text/javascript';
  fileref.src = jsFile;
  head.appendChild(fileref);
}
bmLoader('http://www.joeldare.com/bm/example.js');

Busting Cache

In some cases you might want to bust the JS cache each time you load your js file. In order to do that, I build the following midifications.

javascript:(function(){function%20bmLoader(jsFile){var%20randNum=Math.floor((Math.random()*9999)+1);var%20head=document.getElementsByTagName('head')[0];var%20fileref=document.createElement('script');fileref.type='text/javascript';fileref.src=jsFile+'%3Fcache='+randNum;head.appendChild(fileref);}bmLoader('http://dropbox.dev/ksl/joelFillForm.js');})();

And here's the non-bookmark original.

function bmLoader(jsFile) {
  var randNum = Math.floor((Math.random()*9999)+1);
  var head = document.getElementsByTagName('head')[0];
  var fileref = document.createElement('script');
  fileref.type = 'text/javascript';
  fileref.src = jsFile + '?cache=' + randNum;
  head.appendChild(fileref);
}
bmLoader('http://dropbox.dev/ksl/joelFillForm.js');

A great resource for converting strait JavaScript to a bookmarklet is available at http://chris.zarate.org/bookmarkleter.

comments powered by Disqus
javascript/write_your_own_javascript_bookmarklet.txt · Last modified: 2020/06/01 22:53 (external edit)