如何在第一页加载时执行 JavaScript 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31867229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:18:39  来源:igfitidea点击:

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

javascript

提问by Colin

I am wondering if there is a way to execute a JavaScript function once only on the first ever page load and then not execute on any subsequent reloads.

我想知道是否有办法只在第一次页面加载时执行一次 JavaScript 函数,然后在任何后续重新加载时不执行。

Is there a way I can go about doing this?

有没有办法我可以这样做?

回答by Script47

The code below will execute once the onloadevent fires. The statement checks ifthe onetime functionhas NOTbeen executed before by making use of a flag (hasCodeRunBefore), which is then stored in localStorage.

一旦onload事件触发,下面的代码将执行。该语句检查if一次性功能已经被执行之前通过使标志(的用途hasCodeRunBefore),其然后存储在localStorage

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

Note:If the user clears their browsers' localStorageby any means, then the function will run again because the flag (hasCodeRunBefore) will have been removed.

注意:如果用户localStorage以任何方式清除浏览器,则该函数将再次运行,因为标记 ( hasCodeRunBefore) 已被删除。

Good news...

好消息...

Using localStoragecanbe tedious because of operators and long winded function names. I created a basic moduleto simplify this, so the above code would be replaced with:

由于运算符和冗长的函数名称,使用可能很乏味。我创建了一个基本模块来简化这一点,因此上面的代码将替换为: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... **/ 
        });
    }
};

Update #1

更新 #1

Per @PatrickRoberts comment, you can use the inoperator to see if a variable key exists in localStorage, so

根据@PatrickRoberts 注释,您可以使用in运算符查看localStorage 中是否存在变量键,因此

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

becomes

变成

if (!('hasCodeRunBefore' in localStorage))

and is less verbose and a lot cleaner.

并且不那么冗长,而且更干净。

Secondly, you can set values as you would an object (localStorage.hasCodeRunBefore = true) though it will be stored as a string, not as boolean (or whatever data type your value is).

其次,您可以像设置对象 ( localStorage.hasCodeRunBefore = true)一样设置值,但它会存储为字符串,而不是布尔值(或您的值的任何数据类型)。

回答by zzzzBov

All JavaScript must execute every time a page loads. If the script is on the page, it will execute.

每次加载页面时,所有 JavaScript 都必须执行。如果脚本在页面上,它将执行。

The logicthat is executed within the JavaScript included on the page may execute in a different manner depending on the page state, input provided, and any other signals it receives, be it from the server or the client.

根据页面状态、提供的输入以及它从服务器或客户端接收的任何其他信号,在页面上包含的 JavaScript 中执行的逻辑可能以不同的方式执行。

If you're using a server side language, you might choose to render a script conditionally, such as the first time a user logs in.

如果您使用的是服务器端语言,您可能会选择有条件地呈现脚本,例如用户第一次登录时。

If you need to include the javascript irrespective of context, then you need to listen to other signals.

如果您需要在不考虑上下文的​​情况下包含 javascript,那么您需要收听其他信号。

The simple modern solution is to make use of localStorage. localStoragecan be used to store custom string values on custom key values for any given domain.

简单的现代解决方案是使用localStorage. localStorage可用于在任何给定域的自定义键值上存储自定义字符串值。

The code to make use of this would look like:

使用它的代码如下所示:

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...';

That's all well and good if you just need things to work on the client alone. Sometimes you might need the server to know whether or not the page has been visited before.

如果您只需要单独为客户端工作,那一切都很好。有时您可能需要服务器知道该页面之前是否被访问过。

The (less)simple solution is to use document.cookie:

(不太)简单的解决方案是使用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...';

If you need to defer the execution until the page has finished loading, then simply include the script in an onloadcallback, either by assigning the event to the window:

如果您需要推迟执行直到页面完成加载,那么只需将脚本包含在onload回调中,或者通过将事件分配给窗口:

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

or by binding the event handler to the window:

或者通过将事件处理程序绑定到窗口:

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

回答by Adrian Oprea

It depends on what first page loadmeans to you. It's subjective.

这取决于首页加载对您意味着什么。这是主观的。

If you want the function to fire once the DOM has been parsed, but only the HTML and no other external resources, bind it to the DOMContentLoadedevent.

如果您希望在解析 DOM 后触发该函数,但仅触发 HTML 而没有其他外部资源,请将其绑定到DOMContentLoaded事件。

document.addEventListener('DOMContentLoaded', fn);

Otherwise, if you want to wait for external resources to be loaded and then fire the event, you should bind it to the windowobject's loadevent like so:

否则,如果您想等待加载外部资源然后触发事件,您应该像这样将其绑定到window对象的load事件:

window.addEventListener('load', fn);

Here are some links from the Mozilla Developer Network that explain the what I just said in more detail:

以下是来自 Mozilla 开发人员网络的一些链接,它们更详细地解释了我刚才所说的内容:

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

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

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

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

Good luck!

祝你好运!

回答by Oliver

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