通过<script>在bookmarklet中加载jQuery和jQueryUI时的范围或时间问题

Scope or timing issue while loading jQuery and jQueryUI in bookmarklet via <script>?

本文关键字:jQueryUI 范围 时间 问题 加载 script bookmarklet 通过 jQuery      更新时间:2023-09-26

Edit:详细信息更新,添加Firefox/Chrome行为差异

我试图创建一个bookmarklet,将加载jQuery和jQueryUI。jQuery加载使用javascript,但我想既然jQuery已经加载,我就继续使用它来加载UI。比让它工作我真的想了解为什么这不起作用。我还在思考作用域/闭包等问题。但我只是不明白为什么在firefox $不起作用,但"jQuery"可以!$在Chrome中工作得很好,但我在那里得到一个不同的问题。

指出:
1)在FireBug/FireFox中,我得到'$("head") is undefined'
2)在Chrome "$"工作正常,但jQueryUI调用失败与对象[对象对象]没有方法'dialog'
3)回调保证jQuery加载的时候,我试图使用它。在Firefox中,如果我将"$"替换为"jQuery"(例如jQuery("head")),那么代码就可以工作了!
4)页面上没有其他库已经在使用$
5)更令人沮丧的是,在Firefox中,如果我只是放弃并使用"jQuery"而不是"$",然后从$("#jquilib").load()设置回调来调用第三个函数,jQueryUI函数,如.tabs()和.dialog()是不可用的,即使回调本身是由jQueryUI可用触发的!
6)在Chrome中,如果我使用setTimeout()到100ms, jQueryUI问题就会消失。如果我降低到1毫秒或更低,问题仍然存在

我使用getScript函数从这篇文章:http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet.

下面是我的代码:
function getScript(url,success){
    var script=document.createElement('script');
    script.src=url;
    var head=document.getElementsByTagName('head')[0],
        done=false;
    // Attach handlers for all browsers
    script.onload=script.onreadystatechange = function(){
      if ( !done && (!this.readyState
           || this.readyState == 'loaded'
           || this.readyState == 'complete') ) {
        done=true;
        success();
        script.onload = script.onreadystatechange = null;
        head.removeChild(script);
      }
    };
    head.appendChild(script);
}
function initializejQueryUI(){
    if (typeof jQuery.ui == 'undefined'){
        // jQueryUI library & jQueryUI cupertino theme
        $('head').append("<link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/cupertino/jquery-ui.css' type='text/css' rel='stylesheet'>");
        $('head').append("<script id='jquilib' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js'></script>");
    }
    $("#jquilib").load($("<div>jQuery & UI Loaded!</div>").dialog());
}
getScript('https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js', initializejQueryUI); // call initializejQueryUI as callback when jQuery loads

好了,经过很多的试错,我弄明白了。我继续在Chrome中开发我的脚本,似乎比在Firefox中走得更远。当我完成我的bookmarklet后,我一时兴起在Firefox中尝试了一下,它也在那里工作!以下是我学到的:

1) $("#jquilib").load($("<div>jQuery & UI Loaded!</div>").dialog());调用不起作用,因为jQuery 在处理脚本后从DOM中删除了通过append添加的元素!重用getScript()函数来获取jQueryUI并将警报放在从回调调用的函数中更容易。我遇到的选项卡创建问题(上面问题中的第5项)就是这个怪癖的结果。

参考: http://api.jquery.com/append/
搜索Karl Swedberg说"yes, it's normal"

2) Firebug似乎在控制台中使用了"$",导致了像我上面描述的"$"不起作用但jQuery()起作用的情况。似乎有一些规则管理,当它释放"$",因为如果我只是尝试再次运行脚本jQuery的$快捷方式突然工作。这是最令人沮丧的部分,因为它让它看起来像是一个范围和/或时间问题!

相关文章: