JS不在第一次加载时工作 - 刷新后工作

Tim*_*Tim 5 javascript jquery

我在JS中做了一件相当简单的事情:我正在测试一个元素(基于类名)是否包含一个字符串.

我认为它不起作用的原因是因为元素是通过与onload事件分开的HTTPS请求在页面上呈现的.(类似于嵌入式/ iFrame类型的东西).

我有的脚本示例:

(function($) {

//Only run on a specific page.
if(window.location.href.indexOf("SpecificPageImRunningOn") > -1) {

    //Wait for 3 seconds before running this script, to allow content to load
    setTimeout(function(){

        //Check if a class contains a string "Foobar"
        if($('.aSpecificClass').text().indexOf('Foobar') != -1){
            alert("Yes!");
        }
        else{
            alert("No!");
        }

    }, 3000);

}

})(jQuery);
Run Code Online (Sandbox Code Playgroud)

当我第一次测试它(新浏览器清除缓存)时,它不能按预期工作.

一旦我刷新,它就能很好地工作.

我已经尝试手动触发该功能(通过在所有内容加载后单击按钮)并且它仍然没有任何不同的行为.它在第一次加载时根本不起作用.

我也试过通过设置一个cookie来做一次强制刷新,这似乎没有任何区别.

我想我错过了一些明显的东西!

测试

Sho*_*omz 5

您不应该依赖超时来等待元素准备就绪.第一次运行它时,元素当时没有准备好,而第二次是因为它在第一次运行后被缓存了.

在关闭body标记之前将脚本放在页面底部,或者$(document).ready()在DOM准备好后使用回调运行一次.

  • 哦,这是外在的,抱歉,我错过了.在这种情况下,您需要在该extenal元素上使用侦听器,而不是文档(如`$('iframe').ready()`).你永远不应该依赖一次超时. (3认同)

Tim*_*Tim 1

通过在运行操作之前每 100 毫秒一次又一次检查 window.model(我们目标框架内加载的内容),设法解决了这个问题。

示例代码:

(function($) {

//Only run on a specific page.
if(window.location.href.indexOf("SpecificPageImRunningOn") > -1) {

    function holdOnRecheck() {
        //check if window.model has been defined and that it is not Null before running code. If conditions are not met, wait for 100ms then run the function holdOnRecheck again.
        if (window.model !== undefined && window.model !== null)
        {
            //window model has loaded - good. Now check if the content we are targetting in particular within the model has loaded (judging by its length). If not, wait for 100ms then run the function holdOnRecheck again.
            if (window.model.ABC.length > 0)
            {
                //If you got this far, it's safe to assume that the content has loaded within the model, so you can run whatever you want on the content and it should do something.
                if($('.aSpecificClass').text().indexOf('Foobar') != -1){
                    alert("Yes!");
                }
                else{
                    alert("No!");
                }
                //finish by hiding loading spinner
                document.getElementById("loading").style.display = "none";
            }
            else
            {
                window.setTimeout(holdOnRecheck, 100); 
            }
        }
        else
        {
            window.setTimeout(holdOnRecheck, 100); 
        }
    }   

}
})(jQuery); 
Run Code Online (Sandbox Code Playgroud)