views:

62

answers:

3

I am creating a bookmarklet and the code below is not working on first try. When I goto a page, it says "jQuery is not defined". But, if I click it again, it works perfectly?

var qrcodetogo = {
jQURL: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js',
jQUIURL: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js',
jQUIThemeURL: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/ui-lightness/jquery-ui.css',
init: function(){
    this.createLink('qrcodetogo_UI-Lightness', this.jQUIThemeURL);
    this.createScript('qrcodetogo_jQuery', this.jQURL);
    this.createScript('qrcodetogo_jQueryUI', this.jQUIURL);
    this.createHiddenDiv('qrcodetogo_dialog','This is a Test.');
    jQuery.noConflict();
},

showQRCode: function() {
    jQuery('#qrcodetogo_dialog').dialog();
},

createLink: function(id, url) {
    var l = document.createElement('link');
    l.href = url;
    l.rel = 'stylesheet';
    l.type = 'text/css';
    l.media = 'screen';
    l.charset = 'utf-8';
    document.getElementsByTagName('head')[0].appendChild(l);
},

createScript: function(id, url) {
    var s = document.createElement('script');
    s.src = url;
    s.id = id;
    document.getElementsByTagName('head')[0].appendChild(s);
},

createHiddenDiv: function(id, body) {
    var div = document.createElement('div');
    div.id = id;
    div.innerHTML = body;
    div.style.display = 'none';
    document.getElementsByTagName('body')[0].appendChild(div)
}
}

qrcodetogo.init();
qrcodetogo.showQRCode();
A: 

Maybe you're trying to use jQuery before it's finished downloading and parsing.

Delan Azabani
A: 

You are downloading the code from Google, and most likely, your page is loading and running the Jquery code before the actual library have been fully downloaded from Google... You should place the file where your page is...

Alternatively you can include the jquery library in your index page, thus making it available for the entire website before any calls to it!

Btw: use the file from google it's good, but only if loaded properly!

Zuul
+1  A: 

Dynamically added script tags will go into a queue: first your code will be executed to the end, then any other code already in the queue (other onclick event handlers, for example), and only then the code in the script tag. Put jQuery-dependent code in a separate function, and set it as the event handler for the onload event of the script tag.

Tgr