简体   繁体   中英

In Chrome alert doesn't show HTML until pop up is executed

I just started to learn JavaScript and I have a problem with alert. In Chrome alert doesn't show HTML until pop-up is executed.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript</title>
</head>
<body>
    <h1>JavaScript in HTML</h1>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>

script.js

alert("Helo!");

Add an event listener to the window object and call alert within the event handler, when the load event occurs:

window.addEventListener('load', function() {
  alert('Helo!');
})

 <!DOCTYPE html> <html> <head> <title>JavaScript</title> </head> <body> <h1>JavaScript in HTML</h1> <script> window.addEventListener('load', function () { alert('Helo!'); }) </script> </body> </html> 

Or add an event listener to the document and use setTimeout with a 0 delay to defer the execution of alert within the DOMContentLoaded event handler:

document.addEventListener('DOMContentLoaded', function() {
  setTimeout(function() {
    alert('Helo!');
  }, 0);
});

 <!DOCTYPE html> <html> <head> <title>JavaScript</title> </head> <body> <h1>JavaScript in HTML</h1> <script> document.addEventListener('DOMContentLoaded', function() { setTimeout(function() { alert('Helo!'); }, 0); }); </script> </body> </html> 

With reference to @epascarello's comment, you need to add alert on load of an element or window. Something like this. window.onload = function() {alert('hello');};

This alert is blocking the load of the html. Use lifecycles to call the javascript after the html is loaded.

<script>
window.onload = function() {
    alert("hello")
};
</script>

What this code does is checks to see if the browser window is loaded. When this happens you run a function that contains your script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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