我正在开发一个需要访问jquery-ui以及jquery min的bookmarklet。当然担心页面可能已经加载了jQuery并且应该避免冲突。
在http://benalman.com/code/javascript/jquery/jquery.ba-run-code-bookmarklet.js找到使用Ben Alman的代码我已经能够优雅地引入jQuery并在用户界面中入侵以加载但似乎存在延迟问题和jQuery UI还没准备好马上去......
在执行实际代码之前,有没有更好的方法来按顺序处理两个脚本?
(function( window, document, jQuery, req_version, callback, callback_orig, parent, script ){
if ( !window[jQuery] || req_version > window[jQuery].fn.jquery ) {
parent = document.documentElement.childNodes[0];
script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js';
parent.appendChild(script);
callback_orig = callback;
callback = function($, L) {
'$:nomunge, L:nomunge';
$(script).remove();
callback_orig( $, L );
};
}
if (typeof jQuery.ui == 'undefined'){
parent = document.documentElement.childNodes[0];
scriptui = document.createElement('script');
scriptui.type = 'text/javascript';
scriptui.src = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.js';
parent.appendChild(scriptui);
alert('Loading your matches...');
}
(function loopy($){
'$:nomunge'; // Used by YUI compressor.
( $ = window[jQuery] ) && req_version <= $.fn.jquery
? callback( parent ? $.noConflict(1) : $, !!parent ) : setTimeout( loopy, 50 );
})();
})( window, document, 'jQuery', '1.3.2',
function($,L) {
'$:nomunge, L:nomunge';
<all the jquery stuff goes here>
在Using jQuery UI in a Bookmarklet有一个类似的问题有深入的答案,但我无法将其从CoffeeMarklet转换为“标准”js。
答案 0 :(得分:3)
请参阅我的要点 - 这是一个用于加载jQuery的bookmarklet模板,但您可以在执行前指定其他脚本和css加载。
https://gist.github.com/2897748
你这样初始化它。
编辑:如果您需要加载依赖项,您可以根据不同的条件创建一个数组并将其推入其中。
var jsDependencies = [];
// This will only load jQuery UI if it does not exist already.
// Of course if you rely on the page's copy, you have to do some
// more advanced things to check for versions and whatnot.
if(!window.jQuery || !window.jQuery.ui){
jsDependencies.push('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js');
}
var MyBookmarklet = MyBookmarklet || new Bookmarklet({
// debug: true, // use debug to bust the cache on your resources
css: ['/my/style.css'],
js: jsDependencies,
// jqpath: '/my/jquery.js', // defaults to google cdn-hosted jquery
ready: function(base) { // use base to expose a public method
base.init = function(){
// doStuff();
}
base.init();
}
});