下面的代碼片段是從書JavaScript:明確指南。從「JavaScript:The Definite Guide」使用這個onLoad函數有什麼意義?
我對此有一些疑問。從我的角度來看,我不會預見任何必須使用onLoad
函數的情況。
我認爲這段代碼必須作爲全局JavaScript來使用,而不是作爲事件處理程序的一部分。如果在按鈕的事件處理程序中調用它,則窗口上的加載事件必須已經被觸發。結果,註冊的函數將永遠不會被調用。
但是,如果它被用作全局JavaScript,則在調用onLoad
函數時,onLoad.loaded
總是爲false。
爲什麼不只是在窗口上註冊加載事件,而不是檢查onLoad.loaded
是真是假?
// Register the function f to run when the document finishes loading.
// If the document has already loaded, run it asynchronously ASAP.
function onLoad(f) {
if (onLoad.loaded) // If document is already loaded
window.setTimeout(f, 0); // Queue f to be run as soon as possible
else if (window.addEventListener) // Standard event registration method
window.addEventListener("load", f, false);
else if (window.attachEvent) // IE8 and earlier use this instead
window.attachEvent("onload", f);
}
// Start by setting a flag that indicates that the document is not loaded yet.
onLoad.loaded = false;
// And register a function to set the flag when the document does load.
onLoad(function() {
onLoad.loaded = true;
});
「* onLoad.loaded永遠是假的*」 - 你爲什麼這麼認爲?它在代碼段中顯式設置爲「true」。 – Bergi
當您的應用程序依賴於它們的腳本有很多時,您需要確保它們在您開始運行應用程序之前加載。 – Atrotors
如果您不知道用戶將在何處或如何包含該插件,這對插件可能很有用。如果用戶在頁面加載後動態地包含插件,則分配一個「Document.onLoad」事件處理程序將不會執行任何操作,因爲該頁面已經加載。所以基本上這只是增加了一個抽象層,以允許一個插件無論在哪裏加載都能正確運行 –