views:

290

answers:

2

I am writing some bookmarklets for a project that I am currently working on and I was wondering what the best practice for writing a bookmarklet was. I did some looking around and this is what I came up with

 javascript:void((function()
  {
    var%20e=document.createElement('script');
    e.setAttribute('type','text/javascript');
    e.setAttribute('src','http://someserver.com/bookmarkletcode.js');
   document.body.appendChild(e)
  })())

I felt this is nice because the code can always be changed (since its requested every time) and still it acts like a bookmarklet. Are there are any problems to this approach ? Browser incompatibility etc? What is the best practice for this?

+1  A: 

Looks OK. But if your js file is already cached, it will not be requested every time. So you'd need it to append '?' + new Date() to your src attribute to ensure it is requested every time.

Lee Kowalkowski
True. I agree!!
Ritesh M Nayak
+2  A: 

That bookmarklet will append a new copy of the script to the document every time it is run. For long-lived pages (e.g. Gmail), this could add up to a lot of memory usage, and if loading your script has side effects, they’ll occur multiple times. A better strategy would be to give your script an id, and check for existence of that element first, e.g.:

var s = document.getElementById('someUniqueId');
if (s) {
  s.parentNode.removeChild(s);
}
s = document.createElement('script');
s.setAttribute('src', 'http://example.com/script.js');
s.setAttribute('type', 'text/javascript');
s.setAttribute('id', 'someUniqueId');
document.body.appendChild(s);

N.B. another alternative is to keep the existing script if it’s already in the document. This might save some server traffic if your bookmarklet is used frequently between page reloads. The worst case is that someone is using an older version of your script for a while; if you don’t expect it to change often, that might be fine.

Steven Dee