Help us understand the problem. What is going on with this article?

ロード完了時に任意の処理を実行させる件メモ

More than 1 year has passed since last update.

最近、脱ぢぇーくえりーで既存のコードをES5に書き換えてます。
そしてJQUERYの便利さを痛感しております。

さて、タイトルのようにページ読み込みが完了した段階で何かをしたい場合、JQUERY先生だと

$(function(){
  処理内容
});

でOKです。なんて簡単なんだ!!
これをES5にすると

window.onload = function(){
  処理内容
};

となります。
以上!!
っておーーーーーい!!

この書き方には落とし穴がありましたw
複数のwindow.onloadが存在すると最後のものが上書きされ、それ以前の処理は動きません。

window.onload = function(){
  console.log('Lupin the first');
};
window.onload = function(){
  console.log('Lupin the second');
};
window.onload = function(){
  console.log('Lupin the third');
  // ルパン3世だけ表示される
};

なので、理解した上でwindow.onloadを使うなら良いですが、知らないで乱発すると酷い目にあいますw
では、複数の処理を書きたい場合はどうしたらよいのか?

document.addEventListener('DOMContentLoaded', function(){
  console.log('Lupin the first');
}, false);
document.addEventListener('DOMContentLoaded', function(){
  console.log('Lupin the second');
}, false);
document.addEventListener('DOMContentLoaded', function(){
  console.log('Lupin the third');
}, false);

こんな感じで良さそうです。
DOMContentLoaderdは画像等すべてのリソースが読み込み終わった時に何かをしたい場合はloadで。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away