Vanilla JavaScript 相当于 jQuery 的 $.ready() - 当页面/DOM 准备好时如何调用函数

2022-08-29 21:57:57

使用jQuery,我们都知道这个奇妙的功能:.ready()

$('document').ready(function(){});

但是,假设我想运行一个用标准JavaScript编写的函数,没有库支持它,并且我想在页面准备好处理它时立即启动一个函数。解决这个问题的正确方法是什么?

我知道我可以做到:

window.onload="myFunction()";

或者我可以使用标签:body

<body onload="myFunction()">

或者我甚至可以尝试在页面底部的所有内容之后,但是结尾或标签如下:bodyhtml

<script type="text/javascript">
    myFunction();
</script>

什么是跨浏览器(旧/新)兼容的方法,以像jQuery一样的方式发布一个或多个函数?$.ready()


答案 1

在没有一个可以为您完成所有跨浏览器兼容性的框架的情况下,最简单的事情就是在正文的末尾调用你的代码。这比处理程序执行得更快,因为这只等待 DOM 准备就绪,而不是等待所有映像加载。而且,这适用于每个浏览器。onload

<!doctype html>
<html>
<head>
</head>
<body>
Your HTML here

<script>
// self executing function here
(function() {
   // your page initialization code here
   // the DOM will be available here

})();
</script>
</body>
</html>

对于现代浏览器(来自IE9和更新版本以及任何版本的Chrome,Firefox或Safari),如果您希望能够实现可以从任何地方调用的类似jQuery的方法(而不必担心调用脚本的位置),则可以使用如下内容:$(document).ready()

function docReady(fn) {
    // see if DOM is already available
    if (document.readyState === "complete" || document.readyState === "interactive") {
        // call on next available tick
        setTimeout(fn, 1);
    } else {
        document.addEventListener("DOMContentLoaded", fn);
    }
}    

用法:

docReady(function() {
    // DOM is loaded and ready for manipulation here
});

如果您需要完全的跨浏览器兼容性(包括旧版本的IE),并且您不想等待,那么您可能应该去看看像jQuery这样的框架如何实现其方法。根据浏览器的功能,它相当复杂。window.onload$(document).ready()

为了让您了解jQuery的功能(无论放置脚本标签在哪里,它都可以工作)。

如果支持,它将尝试以下标准:

document.addEventListener('DOMContentLoaded', fn, false);

回退到:

window.addEventListener('load', fn, false )

或者对于旧版本的IE,它使用:

document.attachEvent("onreadystatechange", fn);

回退到:

window.attachEvent("onload", fn);

而且,IE代码路径中有一些我不太遵循的解决方法,但看起来它与框架有关。


以下是用普通javascript编写的jQuery的完整替代品:.ready()

(function(funcName, baseObj) {
    // The public function name defaults to window.docReady
    // but you can pass in your own object and own function name and those will be used
    // if you want to put them in a different namespace
    funcName = funcName || "docReady";
    baseObj = baseObj || window;
    var readyList = [];
    var readyFired = false;
    var readyEventHandlersInstalled = false;

    // call this when the document is ready
    // this function protects itself against being called more than once
    function ready() {
        if (!readyFired) {
            // this must be set to true before we start calling callbacks
            readyFired = true;
            for (var i = 0; i < readyList.length; i++) {
                // if a callback here happens to add new ready handlers,
                // the docReady() function will see that it already fired
                // and will schedule the callback to run right after
                // this event loop finishes so all handlers will still execute
                // in order and no new ones will be added to the readyList
                // while we are processing the list
                readyList[i].fn.call(window, readyList[i].ctx);
            }
            // allow any closures held by these functions to free
            readyList = [];
        }
    }

    function readyStateChange() {
        if ( document.readyState === "complete" ) {
            ready();
        }
    }

    // This is the one public interface
    // docReady(fn, context);
    // the context argument is optional - if present, it will be passed
    // as an argument to the callback
    baseObj[funcName] = function(callback, context) {
        if (typeof callback !== "function") {
            throw new TypeError("callback for docReady(fn) must be a function");
        }
        // if ready has already fired, then just schedule the callback
        // to fire asynchronously, but right away
        if (readyFired) {
            setTimeout(function() {callback(context);}, 1);
            return;
        } else {
            // add the function and context to the list
            readyList.push({fn: callback, ctx: context});
        }
        // if document already ready to go, schedule the ready function to run
        if (document.readyState === "complete") {
            setTimeout(ready, 1);
        } else if (!readyEventHandlersInstalled) {
            // otherwise if we don't have event handlers installed, install them
            if (document.addEventListener) {
                // first choice is DOMContentLoaded event
                document.addEventListener("DOMContentLoaded", ready, false);
                // backup is window load event
                window.addEventListener("load", ready, false);
            } else {
                // must be IE
                document.attachEvent("onreadystatechange", readyStateChange);
                window.attachEvent("onload", ready);
            }
            readyEventHandlersInstalled = true;
        }
    }
})("docReady", window);

最新版本的代码在GitHub上公开共享,网址为 https://github.com/jfriend00/docReady

用法:

// pass a function reference
docReady(fn);

// use an anonymous function
docReady(function() {
    // code here
});

// pass a function reference and a context
// the context will be passed to the function as the first argument
docReady(fn, context);

// use an anonymous function with a context
docReady(function(context) {
    // code here that can use the context argument that was passed to docReady
}, ctx);

这已经在以下方面进行了测试:

IE6 and up
Firefox 3.6 and up
Chrome 14 and up
Safari 5.1 and up
Opera 11.6 and up
Multiple iOS devices
Multiple Android devices

工作实现和测试平台:http://jsfiddle.net/jfriend00/YfD3C/


以下是其工作原理的摘要:

  1. 创建一个IIFE(立即调用的函数表达式),以便我们可以拥有非公共状态变量。
  2. 声明公共函数docReady(fn, context)
  3. 调用 时,检查就绪处理程序是否已触发。如果是这样,只需将新添加的回调安排在 JS 的此线程使用 完成后立即触发即可。docReady(fn, context)setTimeout(fn, 1)
  4. 如果 ready 处理程序尚未触发,请将此新回调添加到稍后调用的回调列表中。
  5. 检查文档是否已准备就绪。如果是这样,请执行所有就绪的处理程序。
  6. 如果我们尚未安装事件侦听器以了解文档何时准备就绪,请立即安装它们。
  7. 如果存在,则安装事件处理程序,同时用于和事件。“加载”是安全方面的备份事件,不应被占用。document.addEventListener.addEventListener()"DOMContentLoaded""load"
  8. 如果不存在,则使用 for 和 事件安装事件处理程序。document.addEventListener.attachEvent()"onreadystatechange""onload"
  9. 在这种情况下,请检查是否和 如果是,则调用函数以触发所有就绪的处理程序。onreadystatechangedocument.readyState === "complete"
  10. 在所有其他事件处理程序中,调用函数以触发所有就绪的处理程序。
  11. 在调用所有就绪处理程序的函数中,检查状态变量以查看我们是否已经触发。如果我们有,什么都不做。如果尚未调用我们,则遍历 ready 函数数组,并按添加顺序调用每个函数。设置一个标志以指示这些都已被调用,因此它们永远不会执行多次。
  12. 清除函数数组,以便可以释放他们可能正在使用的任何闭包。

向 注册的处理程序保证按其注册顺序被触发。docReady()

如果在文档已准备就绪后调用,则将使用 将调度回调在当前执行线程完成后立即执行。这允许调用代码始终假设它们是稍后调用的异步回调,即使稍后是JS的当前线程完成并保持调用顺序。docReady(fn)setTimeout(fn, 1)


答案 2

如果你正在做VANILLA plain JavaScript而没有jQuery,那么你必须使用(Internet Explorer 9或更高版本):

document.addEventListener("DOMContentLoaded", function(event) {
    // Your code to run since DOM is loaded and ready
});

以上是jQuery的等价物:.ready

$(document).ready(function() {
    console.log("Ready!");
});

它也可以写成这样的速记,jQuery将在准备就绪后运行。

$(function() {
    console.log("ready!");
});

不要与以下内容混淆(这并不意味着是DOM就绪):

不要使用像这样自动执行的IIFE

 Example:

(function() {
   // Your page initialization code here  - WRONG
   // The DOM will be available here   - WRONG
})();

此 IIFE 不会等待 DOM 加载。(我甚至在谈论最新版本的Chrome浏览器!