首页 > 解决方案 > 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 */

}

标签: javascript

解决方案


更改分配给的匿名函数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>initCalculatorDOMContentLoadedDOMContentLoaded

为了更加安全,您可以使用dataseton 条目来防止双重初始化<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 ();
}

推荐阅读