javascript - Javascript - 异步加载代码时 window.onload 的替代方案
问题描述
我有一个计算器,我正在集成到我的网站中。通常,当单独在页面上时,计算器会使用以下函数进行初始化
window.onload = function () {
/* Initializes calculator */
}
但是,当用户要求它时,我将这个计算器异步加载到页面上,默认情况下它不在页面上。计算器异步加载到页面后如何初始化?我遇到的问题是,window.onload = function ()
当我将计算器异步加载到页面时,初始化计算器的方法不起作用,因为window.onload
事件已经发生。window.onload
当计算器被异步带到页面时,我应该使用什么函数而不是初始化计算器?
// 1. Page loads
// 2. Calculator is brought to page asynchronously
// 3. Code below executes to initialize the calculator
***something else*** = function () {
/* Initializes calculator */
}
解决方案
更改分配给的匿名函数onload
...
window.onload = function() {
// stuff
};
...到基于直接或间接调用的命名函数,如下所示:document.readyState
function initCalculator() {
// stuff
}
if( document.readyState === 'loading' ) {
document.addEventListener( 'DOMContentLoaded', initCalculator );
}
else if( document.readyState === 'interactive' || document.readyState === 'complete' ) {
initCalculator ();
}
- 如果它
<script>
是普通(静态)HTML 的一部分<head>
并同步加载或使用defer
,则该initCalculator
函数将在'DOMContentLoaded'
触发时运行。 - 如果是带有-
<script>
的普通(静态)HTML 的一部分,或者是在页面加载后添加的,那么如果异步脚本在 之后加载,则该函数将立即运行,或者如果它在之前加载,则它将在适当时运行。<head>
async
<script>
initCalculator
DOMContentLoaded
DOMContentLoaded
为了更加安全,您可以使用dataset
on 条目来防止双重初始化<html>
(这比在 上添加属性更安全window
):
function initCalculator() {
if( document.documentElement.dataset['calcLoaded'] === 'true' ) return;
// do stuff
document.documentElement.dataset['calcLoaded'] = 'true';
}
if( document.readyState === 'loading' ) {
document.addEventListener( 'DOMContentLoaded', initCalculator );
}
else if( document.readyState === 'interactive' || document.readyState === 'complete' ) {
initCalculator ();
}
推荐阅读
- c# - 如何从 firestore 中读取数组字段以及其中的元素,并将其保存回 C# 中的 firestore?
- oauth - 为什么要在服务器端保存刷新令牌?
- ios - 通过将 cookie 从 HTTPCookieStorage 复制到 WKWebsiteDataStore 来设置 WKWebView 的 cookie 时出现问题
- c# - 根据任务 ID 取消任务
- python - 如何在 JSON 键中指定值
- php - PHP定义的奇怪行为()
- python - 需要显示没有提交按钮的多个表单内的输入
- hive - 将具有当前时间戳的列添加到 Hive 中的表
- web-scraping - 如何链接两个 Apify 演员?
- python - 如何返回烧瓶中自我模型的所有元素的列表?