簡體   English   中英

如何在第一頁加載時執行JavaScript函數?

[英]How can I execute a JavaScript function on the first page load?

我想知道是否有一種方法只在第一次頁面加載時執行一次JavaScript函數,然后在任何后續重新加載時不執行。

有沒有辦法可以做到這一點?

一旦onload事件觸發,下面的代碼就會執行。 該語句檢查if 這位當年的功能 尚未之前通過利用標志(的執行hasCodeRunBefore ),然后將其存儲在localStorage

window.onload = function () {
    if (localStorage.getItem("hasCodeRunBefore") === null) {
        /** Your code here. **/
        localStorage.setItem("hasCodeRunBefore", true);
    }
}

注意:如果用戶以任何方式清除其瀏覽器的localStorage ,則該函數將再次運行,因為該標志( hasCodeRunBefore )將被刪除。

好消息...

由於運算符和冗長的函數名稱,使用localStorage 可能會很乏味。 我創建了一個基本模塊來簡化這個,所以上面的代碼將替換為:

window.onload = function () {
    if (!ls.exists('has_code_run_before')) {
        /** Your code here... **/
        ls.set.single('has_code_run_before', true);

        /** or... you can use a callback. **/
        ls.set.single('has_code_run_before', true, function () {
           /** Your code here... **/ 
        });
    }
};

更新#1

根據@PatrickRoberts注釋 ,您可以使用in運算符來查看localStorage中是否存在變量鍵,所以

if (localStorage.getItem('hasCodeRunBefore') === null)

if (!('hasCodeRunBefore' in localStorage))

並且更簡潔,更清潔。

其次 ,您可以像設置對象一樣設置值( localStorage.hasCodeRunBefore = true ),盡管它將存儲為字符串,而不是布爾值(或者您的值是什么數據類型)。

每次加載頁面時都必須執行所有JavaScript。 如果腳本在頁面上,它將執行。

在頁面上包含的JavaScript中執行的邏輯可以以不同的方式執行,這取決於頁面狀態,提供的輸入以及它從服務器或客戶端接收的任何其他信號。

如果您使用的是服務器端語言,則可以選擇有條件地呈現腳本,例如用戶首次登錄時。

如果您需要包含javascript而不考慮上下文,那么您需要收聽其他信號。

簡單的現代解決方案是使用localStorage localStorage可用於在任何給定域的自定義鍵值上存儲自定義字符串值。

使用它的代碼如下所示:

if (localStorage['...my key here...'] === '...my expected value here...') {
    // The page has been visited before
} else {
    // The page has not been visited before
    // OR
    // The user or script has cleared the localStorage value
}
localStorage['...my key here...'] = '...my expected value here...';

如果你只是需要在客戶端工作的東西,這一切都很好。 有時您可能需要服務器知道之前是否訪問過該頁面。

(較少)簡單的解決方案是使用document.cookie

if (/(?:^|;\s*)...my key here...=...my expected value here...(?:;|$)/.test(document.cookie)) {
    // the page has been visited before
} else {
    // The page has not been visited before
    // OR
    // The user or script has cleared the cookie
}
document.cookie = '...my key here...=...my expected value here...';

如果您需要將執行推遲到頁面加載完畢,那么只需將腳本包含在onload回調中,方法是將事件分配給窗口:

window.onload = function () {
    // do stuff when the page has loaded
    //this will override any other scripts that may have been assigned to .onload
};

或者通過將事件處理程序綁定到窗口:

window.addEventListener('load', function () {
    // do stuff when the page has loaded
}, false);

 function toBeExecutedOnFirstLoad(){ // ... } if(localStorage.getItem('first') === null){ toBeExecutedOnFirstLoad(); localStorage.setItem('first','nope!'); } 

這取決於第一頁加載對您意味着什么。 這是主觀的。

如果您希望在解析DOM后觸發該函數,但只需要HTML而不是其他外部資源,請將其綁定到DOMContentLoaded事件。

document.addEventListener('DOMContentLoaded', fn);

否則,如果要等待加載外部資源然后觸發事件,則應將其綁定到window對象的load事件,如下所示:

window.addEventListener('load', fn);

以下是Mozilla開發者網絡的一些鏈接,它們解釋了我剛才所說的內容:

https://developer.mozilla.org/en-US/docs/Web/Events/load

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM