简体   繁体   English

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

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

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? 有没有办法可以做到这一点?

The code below will execute once the onload event fires. 一旦onload事件触发,下面的代码就会执行。 The statement checks if the onetime function has NOT been executed before by making use of a flag ( hasCodeRunBefore ), which is then stored in localStorage . 该语句检查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' localStorage by any means, then the function will run again because the flag ( hasCodeRunBefore ) will have been removed. 注意:如果用户以任何方式清除其浏览器的localStorage ,则该函数将再次运行,因为该标志( hasCodeRunBefore )将被删除。

Good news... 好消息...

Using localStorage can be tedious because of operators and long winded function names. 由于运算符和冗长的函数名称,使用localStorage 可能会很乏味。 I created a basic module to simplify this, so the above code would be replaced with: 我创建了一个基本模块来简化这个,所以上面的代码将替换为:

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 in operator 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 ),尽管它将存储为字符串,而不是布尔值(或者您的值是什么数据类型)。

All JavaScript must execute every time a page loads. 每次加载页面时都必须执行所有JavaScript。 If the script is on the page, it will execute. 如果脚本在页面上,它将执行。

The logic that 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 . 简单的现代解决方案是使用localStorage localStorage can be used to store custom string values on custom key values for any given domain. 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 onload callback, 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);

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

It depends on what first page load means 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 DOMContentLoaded event. 如果您希望在解析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 window object's load event 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! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM