Why is this bookmarklet code saying jQuery is not defined even though jQuery is included?
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 = {开发者_C百科
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();
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.
Maybe you're trying to use jQuery before it's finished downloading and parsing.
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!
You can fix it with a callback:
var createScript = function (id, url, callback) {
var s = document.createElement('script');
s.src = url;
s.id = id;
s.addEventListener('load', callback);
document.getElementsByTagName('head')[0].appendChild(s);
};
createScript("id1", "//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js", function () {
document.write('Loaded');
});
精彩评论