jQueryの読み込まれる順番について一旦整理する
個人的にJavaScript弱いので強化キャンペーン。
jQueryで $(window).load
とか $(document).ready
とか $(function(){})
とかよく分からなくなったので整理というか実験。
ざっくりおさらい
$(document).ready
ready関数を使用してDOMがロードされて操作・解析が可能になったタイミングで関数を実行
$(window).load
DOMがロードされ画像などの関連データの読み込みが完了後処理を実行
実験
読み込んだhtmlファイル
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> //headタグ内のscript <script> console.log("script_head"); $(window).load(function () { console.log("$(window).load_head"); }); $(document).ready(function(){ console.log("$(document).ready_head"); }); $(function(){ console.log("$(function()_head"); }); </script> </head> <body> <div id="content"> <h1>実験だよ</h1> </div> //bodyタグ内のscript <script> console.log("script_body"); $(window).load(function () { console.log("$(window).load_body"); }); $(document).ready(function(){ console.log("$(document).ready_body"); }); $(function(){ console.log("$(function()_body"); }); </script> </body> </html>
結果(console)
sample.html:7 script_head sample.html:34 script_body sample.html:14 ready_head sample.html:18 function_head sample.html:41 ready_body sample.html:45 function_body sample.html:10 load_head sample.html:37 load_body