LoginSignup
7
4

More than 3 years have passed since last update.

window.onloadは同じページで複数回使用することができないのでaddEventListenerを使用する必要がある。

Last updated at Posted at 2019-05-10

参考記事
https://www.sejuku.net/blog/19754

JavaScriptでwindow.onloadを使用する機会があったのですが同じページで二回使ったらものの見事に動きませんでした。

function init() {
      imgs = new Array(3);
    imgs[0] = new Image(250, 207);
    imgs[0].src =  "{% static "javascript/images/pic0.jpg" %}"
    imgs[1] = new Image(250, 207);
    imgs[1].src =  "{% static "javascript/images/pic1.jpg" %}"
    imgs[2] = new Image(250, 207);
    imgs[2].src =  "{% static "javascript/images/pic2.jpg" %}"
}
window.onload = init;

このwindow.onloadは複数使うと一番最後に記載したものだけが反映されます。
というか関数を代入するという構成になっているから関数を代入するたびにその前に代入したものが消えてしまってるんでしょうね。

というわけでこれはこう書き換えます。
```

window.addEventListener("load",function() {
      imgs = new Array(3);
    imgs[0] = new Image(250, 207);
    imgs[0].src =  "{% static "javascript/images/pic0.jpg" %}"
    imgs[1] = new Image(250, 207);
    imgs[1].src =  "{% static "javascript/images/pic1.jpg" %}"
    imgs[2] = new Image(250, 207);
    imgs[2].src =  "{% static "javascript/images/pic2.jpg" %}"
}, false)


function init()を削除して、window.addEventListener("load",function() に書き換えます。無名関数になっていますね。
そして最後に, false)を加えます。
無名関数になって代入もしようがないのでwindow.onload = init;も当然削除ですね。


window.onloadを複数回使いたいときはこのような書き方ならばOK。
試してみてください。

補足
コメントをいただいたのでコードを修正しました。

window.addEventListener("load",function() 

document.addEventListener('DOMContentLoaded', function()

参考記事
https://noumenon-th.net/programming/2017/06/11/domcontentloaded/



実は画像を処理するコードだったのですがこれで特に問題なく動きました。
ありがとうございます!!!

7
4
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4