【问题标题】:IE7 jQuery(document).ready() problemIE7 jQuery(document).ready() 问题
【发布时间】:2011-02-11 01:47:08
【问题描述】:

我有一个在 Firefox 中运行良好的页面,但在 IE 中抛出错误。我正在动态加载 jQuery(如果尚未加载),然后在 jQuery(document).ready() 块中做一些事情。但是,IE 在遇到 jQuery(document).ready() 块时会抛出可怕的“Object expected”错误。

您可以在此处查看完整页面代码:http://www.pastie.org/977767

IE 直接在 jQuery(document).ready() 处抛出错误。

关于这里发生了什么的任何想法?同样,这在 Firefox 中运行良好。似乎 IE 认为 jQuery 已加载但实际上尚未加载,或者当遇到 jQuery(document).ready() 块时 jQuery 仍在加载?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    当您将脚本附加到文档时,它会异步下载。在 IE 中,如下脚本...

    try{
    jQuery(document).ready(function() {
        jQuery.getScript("/CalendarViewer/js/utils.js", function(){
            jQuery.getScript("/CalendarViewer/js/groupcatselector.js", function(){
                jQuery.getScript("/CalendarViewer/js/calendarportlet.js", function(){
                    jQuery.getScript("/CalendarViewer/js/calendarportletmain.js", function(){
                        var cpm = calendarportletmain;
                        cpm.doEditDefaults("V_7f208bca412b42a68c19eb104bf46f14", "/CalendarViewer", groupCats_V_7f208bca412b42a68c19eb104bf46f14);
                    });
                });
            });
        });
    });
    }catch(err){
        alert("error in view.jsp="+err.number+" "+err.description);
    }
    

    ...在 IE 完成下载和解析 jQuery 脚本之前被解析和执行。如果 Firefox 已经缓存了脚本,那么在 Firefox 中可能不是这种情况,它不会花时间下载并且可以立即解析。解析器可能会以不同的方式工作,Firefox 会在脚本下载后立即对其进行解析,而 IE 会排队解析直到线程空闲。

    您可以将此代码移动到setUpJquery 函数的末尾,这意味着它只会在jQuery 对象可用时执行。或者,您可以将代码放在它自己的函数中,然后从 setUpJquery 函数中调用该函数。

    【讨论】:

    • 谢谢,但您看到的代码实际上包含在几个不同的文件中。 jQuery 加载脚本用于许多不同的页面,因此我无法在其中放入特定代码。有没有其他方法可以检查 jQuery(document).ready() 并且只有在 jQuery 实际加载后才对其进行处理?
    • @Zendog74:您可以使 jQuery 成为文档的同步部分。不要使用 DOM 来追加,而是使用 if (typeof jQuery == "undefined") document.write('<script src="jquery.min.js"></script>'); 之类的东西。这将确保在运行其他脚本之前获取 jQuery。
    • 谢谢...做到了。绝对没有那么优雅,但它确实有效。我希望 IE 和 FFX 在加载外部脚本时表现一致,唉。
    【解决方案2】:

    我的解决方法是:

    $(document).ready( function () {
       document_init();
    });
    
    function document_init() {
      try{
    
        checkDivLoaded();
    
        [ ... do more stuff ... ]
    
      } catch( err ) {
        setTimeout('document_init()', 200);
      }
    }
    
    function checkDivLoaded() {
        if ( $('#targetDiv').length == 0) $jquery.error( 'not ready' );
    }
    

    它并不漂亮,但它可以工作......它可以跨多个文件工作,在我能想到的每个浏览器中(我关心的),这意味着您不必弄乱父页面源代码。所以你可以保持标签的清晰。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-23
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 2013-07-19
      • 1970-01-01
      • 2011-08-03
      相关资源
      最近更新 更多