Bookmarklet等到Javascript加载完毕

我有一个加载jQuery和其他一些js库的书签。

我如何能:

  • 等到我正在使用的javascript库可用/加载。 如果我在加载完成之前尝试使用脚本,就像在加载jQuery之前使用$ function一样,会抛出一个未定义的exception。
  • 确保我加载的书签不会被缓存(不使用服务器头,或者很明显,这是一个javascript文件: metatag

有人知道动态添加的javascript的onload是否可以在IE中运行? (与此帖相矛盾)

什么是最简单的解决方案,最清晰的解决这些问题?

这取决于你实际加载jQuery的方式。 如果要向页面添加脚本元素,则可以使用jQuery用于动态加载脚本的相同技术。

编辑 :我做了我的功课,实际上从jQuery代码中提取了一个loadScript函数,用于你的书签。 它实际上可能对许多人(包括我)有用。

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("https://code.jquery.com/jquery-latest.js", function() { $('my_element').hide(); }); 

回答你的第一个问题:Javascript是按顺序解释的,因此在加载库之前,任何后续的bookmarklet代码都不会执行(假设库被解释成功 – 没有语法错误)。

要防止文件被缓存,您可以附加无意义的查询字符串…

 url = 'jquery.js?x=' + new Date().getTime(); 

我注意到在Chrome中使用@Vincent Robert的技术时,加载的脚本顺序是不确定的。 在这种情况下,一点修改有助于:

 (function() { var callback = function() { // Do you work }; // check for our library existence if (typeof (MyLib) == 'undefined') { var sources = [ 'http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js', 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js', 'http://myhost.com/javascripts/mylib.min.js']; var loadNextScript = function() { if (sources.length > 0) { var script = document.createElement('script'); script.src = sources.shift(); document.body.appendChild(script); var done = false; script.onload = script.onreadystatechange = function() { if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) { done = true; // Handle memory leak in IE script.onload = script.onreadystatechange = null; loadNextScript(); } } } else { callback(); } } loadNextScript(); } else { callback(); } })(); 

我对此有所了解,但并不完全。 如果有一个独立的小书签示例,它将演示如何避免缓存,这将是一件好事。