0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-11-30

最近、脱ぢぇーくえりーで既存のコードを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で。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?