简体   繁体   English

html之前运行的脚本

[英]script running before html

I am trying to get the page to load before the script runs. 我试图在脚本运行之前加载页面。 I thought that the script tags going at the bottom of the body would achieve this, however, the alert still pops up first. 我以为位于正文底部的脚本标签可以实现此目的,但是警报仍然会首先弹出。 If anyone knows why please help. 如果有人知道为什么,请帮助。

 <body> <h1>Website!</h1> <p> should load before script</p> <script>alert("hi")</script> </body> 

edit... I have tried the recommended solutions but got the same results as shown here img does the alert function just always run first or am I being stupid? 编辑...我尝试了推荐的解决方案,但是得到了与此处所示相同的结果img警报功能是否总是总是首先运行还是我很愚蠢? Also if it's not clear I am trying to have the contents of the website shown before the alert happens. 另外,如果不清楚,我会在警报发生之前尝试显示网站的内容。

When browser starts loading the HTML and it encounter a <script> it can't continue to build the DOM. 当浏览器开始加载HTML并遇到<script>它将无法继续构建DOM。 It executes the script first and if the script has src it will wait pause building the DOM for external script to load and execute. 它首先执行脚本 ,如果脚本具有src ,它将等待暂停构建DOM,以供外部脚本加载和执行。

Thus you get alert() first then HTML is rendered. 因此,您首先获得alert()然后呈现HTML。 You can use DOMContentLoaded event to wait for DOM to be ready then fire alert() 您可以使用DOMContentLoaded事件来等待DOM准备就绪,然后触发alert()

 <script>
    document.addEventListener("DOMContentLoaded", function(){
        alert("hi")
    });
 </script>

Note: async and defer attribute with script doesn't pause's DOM building and external scripts are loaded in background 注意:带有script asyncdefer属性不会暂停DOM构建,并且外部脚本会在后台加载

 <body> <h1>Website!</h1> <p> should load before script</p> <script> document.addEventListener("DOMContentLoaded", function(){ alert("hi") }); </script> </body> 

Replace alert("hi") with this: 将此替换为alert("hi")

window.onload = () => {
  alert("hi");
};

You can write the following to do a function after the window loads: 您可以在窗口加载后编写以下代码来执行功能:

 <body> <h1>Website!</h1> <p> should load before script</p> <script> window.onload = function(){alert("hi")}; </script> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM