JQuery&s$.ady()的纯JavaScript等价物--当页面/DOM准备就绪时如何调用函数 [英] Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

查看:0
本文介绍了JQuery&s$.ady()的纯JavaScript等价物--当页面/DOM准备就绪时如何调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery,我们都知道.ready()函数:

$('document').ready(function(){});
但是,假设我想要运行一个用标准JavaScript编写的函数,而没有支持它的库,并且我想在页面准备好处理它时立即启动一个函数。解决此问题的正确方法是什么?

我知道我能做到:

window.onload="myFunction()";

或者我可以使用body标记:

<body onload="myFunction()">

或者我甚至可以在页面底部尝试所有内容,但结尾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的任何版本),如果您希望能够实现一个类似$(document).ready()方法的jQuery,您可以从任何地方调用它(而不必担心调用脚本的位置),您只需使用如下内容:

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的作用(它将在放置脚本标记的任何地方工作)。

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

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

回退到:

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

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

document.attachEvent("onreadystatechange", fn);

回退到:

window.attachEvent("onload", fn);

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


以下是用纯Java编写的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)时,检查就绪处理程序是否已经启动。如果是,只需调度新添加的回调在JS的这个线程以setTimeout(fn, 1)结束后立即触发。
  4. 如果就绪处理程序尚未触发,则将此新回调添加到稍后要调用的回调列表中。
  5. 检查文档是否已准备好。如果是,请执行所有就绪处理程序。
  6. 如果我们尚未安装事件侦听器以确定文档何时准备就绪,请立即安装它们。
  7. 如果存在document.addEventListener,则使用.addEventListener()"DOMContentLoaded""load"事件安装事件处理程序。"Load"是安全备份事件,不应使用。
  8. 如果document.addEventListener不存在,则使用.attachEvent()"onreadystatechange""onload"事件安装事件处理程序。
  9. onreadystatechange事件中,检查document.readyState === "complete"是否存在,如果是,则调用一个函数来触发所有就绪的处理程序。
  10. 在所有其他事件处理程序中,调用一个函数以触发所有就绪处理程序。
  11. 在调用所有就绪处理程序的函数中,检查状态变量以查看我们是否已经触发。如果我们有,那就什么都不做。如果我们还没有被调用,那么循环遍历就绪函数数组,并按照添加的顺序调用每个函数。设置一个标志以指示所有这些都已被调用,因此它们永远不会执行多次。
  12. 清除函数数组,以便可以释放它们可能正在使用的任何闭包。

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

如果您在文档已经准备好之后调用docReady(fn),那么将使用setTimeout(fn, 1)在当前执行线程完成后立即执行回调。这允许调用代码始终假定它们是将在以后调用的异步回调,即使稍后是在JS的当前线程完成并且它保持调用顺序时也是如此。

这篇关于JQuery&amp;s$.ady()的纯JavaScript等价物--当页面/DOM准备就绪时如何调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆