繁体   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