The Secret Diary of Han, Aged 0x29

twitter.com/h4n

Archive for February 2008

Including remote javascript in a bookmarklet

The size of a URL is limited to 488 characters in IE 6 SP2. This limits what can be done in a bookmarklet. Fortunately it’s possible to include external javascript. Unfortunately, IE 6 again makes things more difficult that they should be.

To load a remote a remote javascript file, just construct a script tag and insert it into the document body. To call a function, in order to feed it some data stored in the bookmarklet, set the “onload” attribute to a callback to be invoked when loading is ready:

(function() {
  var d=document;
  var s=d.createElement("script");
  s.onload = function() {enter()}; // enter is a function defined in the loaded script
  s.src="/path/to/java/script.js";
  d.body.appendChild(s);
})();

This works nicely in Firefox, Safari and Opera.

The problem is, loading the script is synchronous in IE (both 6 and 7), and the onload callback does not get called. This in spite of MSDN documentation claiming that onload on script tags is honored. However, since loading is synchronous, the script will have completed loading in IE when the appendChild call returns. A workaround, then, is to call the callback explicitly after the appendChild call, but guard it with a flag so that it is run only once.

(function() {
  var d=document;
  var s=d.createElement("script");
  s.onload = function() {enter()}; // enter is a function defined in the loaded script
  s.src="/path/to/java/script.js";
  d.body.appendChild(s);
  if (window.enter)
    enter();
})();

// "enter" function in included javascript file:
var entered = false;
function enter() {
  if (entered)
    return;

  entered = true;
  //...
}     

Advertisements

Written by Han

February 2, 2008 at 18:51

Posted in Uncategorized

Tagged with