有了jQuery,我们都知道奇妙的.ready()函数:

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

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

我知道我能做到:

window.onload="myFunction()";

或者我可以使用body标签:

<body onload="myFunction()">

或者我甚至可以try 在页面底部完成所有操作,但末尾bodyhtml标记如下:

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

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

推荐答案

如果没有一个框架为您提供所有跨浏览器兼容性,最简单的方法就是在正文末尾调用代码.这比onload处理程序执行得更快,因为它只等待DOM准备就绪,而不是等待加载所有图像.而且,这适用于所有浏览器.

<!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),并且不想等待window.onload,那么您可能应该看看像jQuery这样的框架是如何实现其$(document).ready()方法的.这取决于浏览器的功能.

让您稍微了解一下jQuery的功能(无论脚本标记放在哪里,它都可以工作).

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

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. 调用docReady(fn, context)时,判断ready处理程序是否已启动.如果是这样的话,只需将新添加的回调安排在这个JS线程完成setTimeout(fn, 1)后立即启动即可.
  4. 如果就绪处理程序尚未启动,则将此新回调添加到稍后要调用的回调列表中.
  5. 判断文件是否已经准备好.如果是这样,请执行所有就绪的处理程序.
  6. 如果我们还没有安装事件侦听器,还不知道文档何时准备就绪,那么现在就安装它们.
  7. 如果存在document.addEventListener,则使用.addEventListener()"DOMContentLoaded""load"事件安装事件处理程序."负载"是出于安全考虑的备份事件,不需要.
  8. 如果document.addEventListener不存在,则使用.attachEvent()"onreadystatechange""onload"事件安装事件处理程序.
  9. onreadystatechange事件中,判断document.readyState === "complete"是否正确,如果正确,则调用一个函数来触发所有就绪的处理程序.
  10. 在所有其他事件处理程序中,调用一个函数来激发所有就绪的处理程序.
  11. 在调用所有就绪处理程序的函数中,判断一个状态变量,看看我们是否已经触发了.如果我们有,什么也不做.如果我们还没有被调用,那么在ready函数数组中循环,并按照添加的顺序调用每个函数.设置一个标志来指示这些都已被调用,这样它们就不会被多次执行.
  12. 清除函数数组,这样就可以释放它们可能使用的任何闭包.

注册为docReady()的处理程序保证按照注册顺序被解雇.

如果在文档准备就绪后调用docReady(fn),则回调将被安排在当前执行线程使用setTimeout(fn, 1)完成后立即执行.这允许调用代码始终假定它们是稍后将调用的异步回调,即使稍后JS的当前线程完成并保留调用顺序时也是如此.

Javascript相关问答推荐

如何解决(不忽略)reaction详尽的linter规则,而不会在获取数据时导致无限的reender循环

使用useParams路由失败

JS、C++和C#给出不同的Base 64 Guid编码结果

docx.js:如何在客户端使用文档修补程序

浮动Div的淡出模糊效果

空的结果抓取网站与Fetch和Cheerio

使用Google API无法进行Web抓取

material UI按钮组样式props 不反射

为什么123[';toString';].long返回1?

触发异步函数后不能显示数据

如何在Java脚本中对列表中的特定元素进行排序?

Docent.cloneNode(TRUE)不克隆用户输入

是否可以将异步调用与useState(UnctionName)一起使用

无法设置RazorPay订阅API项目价格

如何找到带有特定文本和测试ID的div?

如何使用抽屉屏幕及其子屏幕/组件的上下文?

如何在独立的Angular 应用程序中添加Lucide-Angel?

Firefox的绝对定位没有达到预期效果

Refine.dev从不同的表取多条记录

当S点击按钮时,我如何才能改变它的样式?