de la fenêtre.onload dans le script externe est ignorée en 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. Quand window.onload est utilisé en html, window.onload de js externe sera ignoré.
  2. Quand window.onload de js externe est commenté, bar.length renvoie 0.
  3. Quand window.onload de html est supprimé, window.onload de js externe fonctionne très bien.

Quelqu'un peut-il expliquer pourquoi je ne peux pas utiliser les deux window.onload?

Si je avait à utilisation window.onload en html, comment faire pour savoir si la fenêtre est chargé de js externe?

Pourquoi ne pas vous essayez d'utiliser un autre texte en fonction d'alerte pour le fichier js externe, pour voir où il chargé?

OriginalL'auteur user1643156 | 2013-04-01