views:

1463

answers:

3

I've got a bookmarklet which loads jQuery and some other js libraries.

How do I:

  • Wait until the javascript library I'm using is available/loaded. If I try to use the script before it has finished loading, like using the $ function with jQuery before it's loaded, an undefined exception is thrown.
  • Insure that the bookmarklet I load won't be cached (without using a server header, or obviously, being that this is a javascript file: a metatag)

Is anyone aware if onload for dynamically added javascript works in IE? (to contradict this post)

What's the simplest solution, cleanest resolution to these issues?

+1  A: 

To answer your first question: Javascript is interpreted sequentially, so any following bookmarklet code will not execute until the library is loaded (assuming the library was interpreted successfully - no syntax errors).

To prevent the files from being cached, you can append a meaningless query string...

url = 'jquery.js?x=' + new Date().getTime();
Josh Stodola
Apparently, dynamically added javascript doesn't work exactly as you describe. The element is added by the addElement DOM function and immediately returns. onLoad helps, but I'm disturbed by this post: http://answers.google.com/answers/threadview?id=595949
altCognito
A: 

I got a little closer with this, but not completely. It would be nice to have a discrete, example of a bookmarklet that demonstrated how to avoided caching.

altCognito
+5  A: 

It depends on how you are actually loading jQuery. If you are appending a script element to the page, you can use the same technique that jQuery uses to dynamically load a script.

EDIT: I did my homework and actually extracted a loadScript function from the jQuery code to use in your bookmarklet. It might actually be useful to many (including me).

function loadScript(url, callback)
{
 var head = document.getElementsByTagName("head")[0];
 var script = document.createElement("script");
 script.src = url;

 // Attach handlers for all browsers
 var done = false;
 script.onload = script.onreadystatechange = function()
 {
  if( !done && ( !this.readyState 
     || this.readyState == "loaded" 
     || this.readyState == "complete") )
  {
   done = true;

   // Continue your code
   callback();

   // Handle memory leak in IE
   script.onload = script.onreadystatechange = null;
   head.removeChild( script );
  }
 };

 head.appendChild(script);
}


// Usage: 
// This code loads jQuery and executes some code when jQuery is loaded
loadScript("http://code.jquery.com/jquery-latest.js", function()
{
 $('my_element').hide();
});
Vincent Robert
piece of art :)
vsync
you don't need to specify type="text/javascript" ?
vsync