views:

60

answers:

2

Hey all,

I'm trying to build a bookmarklette. I want to minimize the size of the javascript within the bookmarklette so that I can maintain most of the code in an external file. My goal is to...
1) Add an external .js file to the page.
2) Call a function from that external .js file.
3) Have that function add additional .js files to the page (a JQuery source for instance).

Here is my code for number 1. It works.

javascript:function bmksMain(){var script=document.createElement('script');script.src='http://localhost/bmks/bmksBmkMain.js';scriptObj=document.body.appendChild(script);}bmksMain();

Here is the contents of the .js file.

function bmksBmkMaster(){
      alert('debug1');
    var script, object;
    script = document.createElement('script');
    script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
    object = document.body.appendChild(script);
      alert('debug2');
    $("body").hide();
      alert('debug3');
}
bmksBmkMaster();

When I paste the bookmarklette code into an address bar and execute, debugs 1 and 2 fire and then it dies. Then, if I execute again without refreshing the page, all three debugs fire and it all works perfectly.

Can I not include a .js and use it in within the same function/script? Something funky is going on...

Thanks in advance!

(tested in IE7 and latest Chrome)

A: 

Check the jQuerify Bookmarklet article and its successors for an example of how this should be done. (For example, taking the global $ identifier is not wise.)

Tgr
Thanks! It's a winner!
Nate
A: 

Here is a cross browser way to load scripts:

function loadScript(scriptUrl, callback){
    var script = document.createElement('script');
    script.type='text/javascript';
    script.onload = function(){
        callback(); 
            callback = function(){};

    }
    script.onreadystatechange = function () {
        if(script.readyState === 'loaded' || script.readyState === 'complete'){
            callback();
                    callback = function(){};
        } 
    }
    script.src = scriptUrl;
    document.getElementsByTagName('head').item(0).appendChild(script);
}

You can use it like this:

loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js', function(){
  //hide body
});
letronje
IIRC this can cause `callback` to be called twice (in some versions of Opera, I think). Set `callback` to `function() { }` after calling it as a quick fix.
strager