Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

window.onload in external script gets ignored in Javascript

index.html

<html>
<head>
<script type="text/javascript" src="foo.js"></script>
<script type="text/javascript">
window.onload = function() {
    console.log("hello from html");
};
</script>
</head>
<body>
<div class="bar">bar</div>
</body>
</html>

foo.js

// this js file will be completely ignored with window.onload
//window.onload = function() {

    console.log("hello from external js");

    var bar = document.getElementsByClassName("bar");

    // this returns 0 instead of 1
    console.log(bar.length);
//};
  1. When window.onload is used in html, window.onload from external js will be ignored.
  2. When window.onload from external js is commented out, bar.length returns 0.
  3. When window.onload from html is removed, window.onload from external js works fine.

Can anyone explain why I can't use both window.onload?

If I had to use window.onload in html, how do tell if window is loaded from external js?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

1)The way you're binding, you can have just one method attached to an event. You need to add an event listener for what you want.

window.addEventListener("load", function() { alert("hello!");});

Setting directly a method to the onload event will replace any previously attached method. But if you use listeners instead, you can have many of them bound to an event.

2)If you comment out the onload in your external file, when the document.getElementsByClassName("bar") is called, your document isn't ready yet, then, it will return 0 items.

3)Use the addEventListener as I explained in the first point. If you apply this in both places, it will work like a charm.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...