【问题标题】:window.onload doesn't load the body before script runswindow.onload 在脚本运行之前不加载正文
【发布时间】:2017-11-11 01:22:19
【问题描述】:

在页面完全加载之前没有运行脚本的情况下,我在 HTML 文档中编写 javascript 时遇到了问题。我已将代码精简为非常基本的代码,以尝试消除我可能做错的所有事情。我想在函数init() 运行之前加载页面,并使用window.onload 来执行此操作。但是,该函数的警报会在页面加载之前运行。无论我将脚本放在头部还是正文中,都会发生这种情况。我没有错吗?提前致谢!

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>

    <h1>Green Planet</h1>
    <p id="greenplanet">All is well</p>

    <h1>Red Planet</h1>
    <p >Nothing to report</p>

    <h1 >Blue Planet</h1>
    <p >All systems A-OK</p>

    <script>
        function init() {
            var planet = document.getElementById("greenplanet");
            planet.innerText = "Red Alert: hit by phaser fire!";
            planet.setAttribute("class","redtext");
            alert("it initialized");
        }
        window.onload=init;
    </script>
</body>
</html> 

【问题讨论】:

  • 代码显示works fine here
  • 是什么让您认为页面没有加载?你检查过你的控制台是否有错误?
  • 我正在使用 Chrome 并且在页面的其余部分加载之前显示警报并且网页是白色的。
  • 尝试删除警报。在多个浏览器中对我来说都很好
  • 警报是在页面加载之前显示函数正在触发的方式。如何在函数触发之前让页面完全加载?

标签: javascript html


【解决方案1】:

您的意思是您希望页面在函数执行之前完全呈现?如果是这样,您可以将函数的主体包装在对window.setTimeout() 的调用中。例如,这将在执行您的函数之前完全呈现页面一秒钟:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>

    <h1>Green Planet</h1>
    <p id="greenplanet">All is well</p>

    <h1>Red Planet</h1>
    <p >Nothing to report</p>

    <h1 >Blue Planet</h1>
    <p >All systems A-OK</p>

    <script>
        function init() {
            window.setTimeout(function() {
                var planet = document.getElementById("greenplanet");
                planet.innerText = "Red Alert: hit by phaser fire!";
                planet.setAttribute("class","redtext");
                alert("it initialized");
            }, 1000);
        }
        window.onload=init;
    </script>
</body>
</html>

【讨论】:

  • Alien(又名 Ridley Scott Fan),非常感谢!这正是我所需要的。我的挑战在于 Chrome 和 Safari——Firefox 似乎可以正确加载我的原始代码。您的解决方案解决了我的问题。感谢您抽出宝贵时间提供帮助!
  • @Clairol:我很高兴能帮上忙,我也很高兴你也是 Ridley Scott 的粉丝。 :) 请接受我的回答(点击复选标记),以便其他人清楚这是可接受的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 2018-08-16
  • 2021-05-26
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多