戻る

onload時点で画面サイズを取得
window.onloadとDOMContentLoadedイベントの違い

window.onloadを使用した例
copy
window.onload = function() 
{
	const width = window.innerWidth;
	const height = window.innerHeight;
	console.log("画面幅: " + width + "px, 画面の高さ: " + height + "px");
};
全ての処理が終わったあとで実行されます。
※ページのすべてのリソース(HTML、CSS、JavaScript、画像など)が
完全に読み込まれた後に実行。

DOMContentLoadedイベントを使用した例
copy
document.addEventListener('DOMContentLoaded', function()
{
	const width = window.innerWidth;
	const height = window.innerHeight;
	console.log("画面幅: " + width + "px, 画面の高さ: " + height + "px");
});
HTMLの解析が完了し、DOMツリーが構築された時点で実行されます。
画像や外部リソースの読み込みを待たずに、サイズを取得できます。


window.innerWidth
ブラウザウィンドウの表示領域の幅をピクセルで返します。

window.innerHeight
ブラウザウィンドウの表示領域の高さをピクセルで返します。

結果
window.onload
正確な結果を取得できます。
体感速度が遅くなります。

DOMContentLoadedイベント
ウィンドウサイズが変更されたタイミングによってサイズの取得結果が変わります。
体感速度が早くなります。
ページが完全に読み込まれる前にウインドウの画面を拡縮したとします。
DOMContentLoadedイベントが解析後、サイズが767pxとします。
画面をリサイズして、サイズが1000pxに変更したと仮定します。
しかし、画面サイズは、767pxとして使用する可能性があります。



戻る
back

Get screen size at onload
Difference between window.onload and DOMContentLoaded events

Example using window.onload
copy
window.onload = function() 
{
	const width = window.innerWidth;
	const height = window.innerHeight;
	console.log("screen width: " + width + "px, screen height: " + height + "px");
};
It is executed after all processing is completed.
* It is executed after all resources of the page (HTML, CSS, JavaScript, images, etc.) are
completely loaded.

Example using the DOMContentLoaded event
copy
document.addEventListener('DOMContentLoaded', function()
{
	const width = window.innerWidth;
	const height = window.innerHeight;
	console.log("screen width: " + width + "px, screen height: " + height + "px");
});
Executed when HTML parsing is complete and the DOM tree is constructed.
You can get the size without waiting for images and external resources to load.


window.innerWidth
Returns the width of the browser window's display area in pixels.

window.innerHeight
Returns the height of the browser window's display area in pixels.

Result
window.onload
You can get accurate results.
The perceived speed will be slower.

DOMContentLoaded event
The size acquisition result will change depending on when the window size is changed.
The perceived speed will be faster.
Let's say you resize the window screen before the page is completely loaded.
After the DOMContentLoaded event is analyzed, the size is 767px.
Let's say you resize the screen and the size is changed to 1000px.
But the screen size might be used as 767px.



back



著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。