JavaScript 中的 window.onload 與 onDocumentReady
在 JavaScript 中,`window.onload` 和 `document.ready()` 是頁面載入時使用的兩種方法。
Window.onload
`window.onload` 方法在整個網頁載入完成後執行。這包括與 DOM 相關的所有元素,例如 head 標籤、title 標籤以及所有其他標籤,包括樣式表、影像和影片。`onload` 方法透過向其傳遞函式來使用。該呼叫的函式將在物件載入後執行。
語法
這是 `onload` 方法的語法:
Window.onload = function() Window.onload = (event) => {} //arrow function
示例 1
此示例演示 `window.onload` 在 JavaScript 中的工作方式:
<!DOCTYPE html> <html lang="en"> <head> <title>window.onload()</title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <script> window.onload = (event) => { console.log("The first call will not be loaded if there are two window.onload calls"); }; window.onload = (event) => { console.log("The second call is loaded while using window.onload"); }; </script> </head> <body id="body"> <h1>window.onload()</h1> </body> </html>
輸出
這是執行上述程式碼時在控制檯中顯示的輸出:
The second call is loaded while using window.onload
在上面的示例中,有兩個 `window.onload` 函式呼叫。但它只顯示第二個呼叫的內容。這是因為當使用 `window.onload` 時,內容將在頁面直接載入時載入。
Windows.ready (應為 `document.ready`,jQuery 方法)
因此,如果可能會有多個 `window.onload` 函式呼叫,則將執行最後一個。當 DOM(文件物件模型)載入完畢時,將發生 `ready` 事件。這是 jQuery 的 `$(document).ready()` 方法,而非原生 JavaScript 的 `window.ready`。
由於此事件發生在文件準備就緒之後,因此所有其他 jQuery 事件和函式的最佳位置都在此事件中。如下面的示例所示。`ready()` 方法指定了發生 `ready` 事件時會發生什麼。
語法
`document.ready` 函式語法如下:
$(document).ready(function () { //statements. }); < body onload= " " > and the ready() method shouldn't be used together.
示例
此示例演示 `onDocumentReady` 在 JavaScript 中的工作方式:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { $("button").click(function () { $("p").slideToggle(); }); }); </script> </head> <body> <p>onDocumentready is used, then after the document is loaded then the functionality will be shown which reduces the errors </p> <button>Click to hide</button> </body> </html>
廣告