我想知道是否有一种方法可以仅在第一次页面加载时执行 JavaScript 函数,然后不在任何后续重新加载中执行该函数。
我能否找到一种解决方法?
我想知道是否有一种方法可以仅在第一次页面加载时执行 JavaScript 函数,然后不在任何后续重新加载中执行该函数。
我能否找到一种解决方法?
onload
事件触发后执行。该语句通过使用标志(hasCodeRunBefore
),并将其存储在localStorage
中,检查一次性函数是否已经被执行过,if
没有被执行过。请注意保留{和}符号。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... **/
});
}
};
根据@PatrickRoberts的评论,你可以使用in
运算符来查看localStorage中是否存在一个变量键,因此
if (localStorage.getItem('hasCodeRunBefore') === null)
变成
if (!('hasCodeRunBefore' in localStorage))
localStorage.hasCodeRunBefore = true
),但它将被存储为字符串,而不是布尔值(或任何其他数据类型)。Storage
对象作为普通对象,但需要注意所有值都必须是字符串。例如,您可以通过'hasCodeRunBefore' in localStorage
来检查是否存在,并通过localStorage.hasCodeRunBefore = true
来设置它。 - Patrick Roberts!'foo' in {}
vs. !('foo' in {})
- Patrick RobertslocalStorage
。 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);
这要看你对于“首次页面加载”是什么意思,因为这是主观的。
如果你想让函数在DOM解析后执行,但只有HTML而没有其他外部资源,请将其绑定到DOMContentLoaded
事件。
document.addEventListener('DOMContentLoaded', fn);
window
对象的 load
事件上,像这样:
window.addEventListener('load', fn);
这里有一些来自 Mozilla 开发者网络的链接,可以更详细地解释我刚才说的内容:
https://developer.mozilla.org/zh-CN/docs/Web/Events/load
https://developer.mozilla.org/zh-CN/docs/Web/Events/DOMContentLoaded
祝好运!
function toBeExecutedOnFirstLoad(){
// ...
}
if(localStorage.getItem('first') === null){
toBeExecutedOnFirstLoad();
localStorage.setItem('first','nope!');
}
fun_RunOnlyOnFirstPageLoad(){}
if(!$window.sessionStorage.getItem(hasRunBefore)){
fun_RunOnlyOnFirstPageLoad();
$window.sessionStorage.setItem(hasRunBefore, true);
}
localStorage
来处理的。 - zzzzBov