如何在第一页加载时执行JavaScript函数? [英] How can I execute a JavaScript function on the first page load?
问题描述
我想知道是否有一种方法只在第一次页面加载时执行一次JavaScript函数,然后在任何后续重新加载时都不执行。
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.
是否存在我可以这样做吗?
Is there a way I can go about doing this?
推荐答案
以下代码将在 onload
事件触发。该声明检查 如果
一次性函数之前已经执行 NOT ,则使用标志( hasCodeRunBefore
),然后存储在 localStorage的
。
The code below will execute once the onload
event fires. 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
.
window.onload = function () {
if (localStorage.getItem("hasCodeRunBefore") === null) {
/** Your code here. **/
localStorage.setItem("hasCodeRunBefore", true);
}
}
注意:如果用户清除浏览器的 localStorage
无论如何,该函数将再次运行,因为标志( hasCodeRunBefore
)将被删除。
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
因为操作员和长卷功能而会很乏味名。我创建了一个基本的模块来简化这个,所以上面的代码将替换为:
Using localStorage
can be tedious because of operators and long winded function names. 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... **/
});
}
};
更新#1
Per @PatrickRoberts评论,您可以使用 在
运算符中查看localStorage中是否存在变量键,所以
Update #1
Per @PatrickRoberts comment, you can use the in
operator to see if a variable key exists in localStorage, so
if (localStorage.getItem('hasCodeRunBefore') === null)
成为
if (!('hasCodeRunBefore' in localStorage))
并且更简洁,更清洁。
其次,您可以设置像对象一样的值( localStorage.hasCodeRunBefore = true
)虽然它将被存储为字符串,而不是布尔值(或者您的值是什么数据类型)。
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).
这篇关于如何在第一页加载时执行JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!