在Bookmarklet中使用jQuery UI

在CoffeeScript中,虽然此代码几乎与JavaScript相同:

tabs_html = "

something1

something2

" $("#nm-toolbar").append(tabs_html) $("#nm-container").tabs()

它不起作用。 有趣的是它在尝试最后一行时确实有效:来自控制台的$("#nm-container").tabs() 。 我附上下面的完整代码。 请注意,我正在使用CoffeeMarklet生成似乎仅适用于chrome的bookmarklet。

 s1 = window.document.createElement('script') s1.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js' window.document.body.appendChild(s1) $ -> s2 = window.document.createElement('script') s2.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js' window.document.body.appendChild(s2) jqueryUIcss = window.document.createElement('link') jqueryUIcss.rel = 'stylesheet' jqueryUIcss.type = 'text/css' jqueryUIcss.href = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/blitzer/jquery-ui.css' window.document.head.appendChild(jqueryUIcss) if $("#nm-toolbar").length == 0 toolbar = "
" $("body").append(toolbar) $("#nm-toolbar").css({ 'background': '#fafafa', 'height': '500px', 'width': '400px', 'position': 'fixed', 'bottom': '0px', 'right': '20px', 'padding': '5px' }) tabs_html = "

something1

something2

" $("#nm-toolbar").append(tabs_html) $("#nm-container").tabs()

我怀疑问题是你是异步加载jQuery UI。 这条线

 window.document.body.appendChild(s2) 

开始加载jQuery UI,但是在jQuery UI必须加载之前你的代码仍在继续。 这可以解释为什么在代码中调用tabs()失败,但是在脚本有时间加载后,从控制台执行它会成功。

您应该能够通过使其余代码从回调运行来解决此问题

 s2.onreadystatechange = -> return unless @readyState is 'complete' # the rest of the code goes here 

编辑 :就此而言,你真的应该用s1做同样的事情,否则$ ->调用可能会失败。 它成功的事实表明你在浏览器中缓存了jQuery,或者页面上已经有jQuery。 您还应该使用noConflict来避免覆盖页面的现有jQuery版本。 Acorn链接的Run jQuery Code Bookmarklet可以完成所有这些工作(并且以比本答案中的代码更跨浏览的方式)。

这应该工作:

 ((window, document, requirements, callback) -> getScript = (url, callback) -> script = document.createElement('script') script.src = url head = document.documentElement.childNodes[0] done = false script.onload = script.onreadystatechange = -> if not done and (not (readyState = @readyState) or readyState == 'loaded' or readyState == 'complete') done = true callback() script.onload = script.onreadystatechange = null head.removeChild script head.appendChild script if not ($ = window.jQuery) or requirements['jq'] > $.fn.jquery getScript 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js', -> getScript 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.js', -> callback window.jQuery.noConflict(1) else if not (jqui_version = window.jQuery.ui.version) or requirements['jqui'] > jqui_version getScript 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.js', -> callback window.jQuery.noConflict(1) else callback window.jQuery.noConflict(1) ) window, document, {jq: '1.6.1', jqui: '1.8.7'}, ($) -> # Your code goes here: alert "jq: #{$.fn.jquery}, jqui: #{$.ui.version}" 

如果使用上面的代码,您需要取消选中CoffeeMarklet页面上的“添加jQuery”选项

更新:添加了对jQuery和jQuery UI存在的检查,因此不会不必要地加载它。

虽然可以通过检查Ben Almans代码是否已经存在正确版本的jQuery来改进它。

归因:

Beygi给了一个可爱的片段 ,一个接一个地加载javascript资源。