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

时间:2012-03-27 23:57:22

标签: javascript jquery html

好吧,这可能只是一个愚蠢的问题,但我确信还有很多其他人不时会问同样的问题。我,我只是想以任何方式100%确定。使用jQuery,我们都知道精彩的

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

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

我知道我能做到:

window.onload="myFunction()";

...或者我可以使用body标记:

<body onload="myFunction()">

...或者我甚至可以在所有内容后尝试页面底部,但结束bodyhtml标记如:

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

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

9 个答案:

答案 0 :(得分:1614)

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

<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>

如果你真的不想这样做并且你需要跨浏览器兼容性并且你不想等待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代码路径中有一些我没有完全遵循的解决方法,但看起来它与帧有关。


以下是用简单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)时,检查就绪处理程序是否已经触发。如果是这样,只需在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. 清除函数数组,以便释放它们可能正在使用的任何闭包。
  13. 使用docReady()注册的处理程序可以保证按照注册顺序被解雇。

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

答案 1 :(得分:135)

我想在此处提及一些可能的方法以及适用于所有浏览器的纯javascript技巧

// with jQuery 
$(document).ready(function(){ /* ... */ });

// shorter jQuery version 
$(function(){ /* ... */ });

// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){ 
    // your code goes here
}, false);

// and here's the trick (works everywhere)
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
// use like
r(function(){
    alert('DOM Ready!');
});

正如original author所解释的那样,我们正在检查 document.readyState 属性。如果它包含字符串in(如uninitializedloading中的前两个DOM ready states中的5个),我们会设置超时并再次检查。否则,我们执行传递的函数。

这里的jsFiddle适用于所有浏览器的技巧。

感谢Tutorialzine在本书中加入此内容。

答案 2 :(得分:114)

如果您在没有jQuery的情况下执行 VANILLA 普通 JavaScript ,则必须使用(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!");
});

哪个ALSO可以这样编写SHORTHAND,jQuery将在准备就绪后运行occurs

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

不要与以下相混淆(这不是为DOM准​​备好的):

请勿使用自行执行的IIFE

 Example:

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

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

答案 3 :(得分:75)

在IE9和最新的Firefox和Chrome中测试过,并且在IE8中也得到了支持。

document.onreadystatechange = function () {
  var state = document.readyState;
  if (state == 'interactive') {
      init();
  } else if (state == 'complete') {
      initOnCompleteLoad();
  }
}​;

示例:http://jsfiddle.net/electricvisions/Jacck/

更新 - 可重复使用的版本

我刚开发了以下内容。这是一个相当简单的等效于jQuery或Dom准备就绪,没有向后兼容性。它可能需要进一步完善。测试了最新版本的Chrome,Firefox和IE(10/11),并且应该在旧版浏览器中使用。如果我发现任何问题,我会更新。

window.readyHandlers = [];
window.ready = function ready(handler) {
  window.readyHandlers.push(handler);
  handleState();
};

window.handleState = function handleState () {
  if (['interactive', 'complete'].indexOf(document.readyState) > -1) {
    while(window.readyHandlers.length > 0) {
      (window.readyHandlers.shift())();
    }
  }
};

document.onreadystatechange = window.handleState;

用法:

ready(function () {
  // your code here
});

它是为处理JS的异步加载而编写的,但您可能希望首先同步加载此脚本,除非您正在缩小。我发现它在开发中很有用。

现代浏览器还支持脚本的异步加载,这进一步增强了体验。支持异步意味着可以在呈现页面的同时同时下载多个脚本。根据异步加载的其他脚本或使用minifier或类似browserify来处理依赖项时,请注意。

答案 4 :(得分:17)

HubSpot的优秀人员拥有一个资源,您可以在其中找到纯Javascript方法,以实现很多jQuery的优点 - 包括ready

http://youmightnotneedjquery.com/#ready

function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', fn);
  } else {
    document.attachEvent('onreadystatechange', function() {
      if (document.readyState != 'loading')
        fn();
    });
  }
}

示例内联用法:

ready(function() { alert('hello'); });

答案 5 :(得分:7)

您的方法(在关闭正文标记之前放置脚本)

<script>
   myFunction()
</script>
</body>
</html>

是支持新旧浏览器的可靠方式。

答案 6 :(得分:4)

我不太确定你在问什么,但也许这会有所帮助:

window.onload = function(){
    // Code. . .

}

或者:

window.onload = main;

function main(){
    // Code. . .

}

答案 7 :(得分:3)

这是一个清理过的,非评估使用版本的Ram-swaroop's“适用于所有浏览器”各种 - 适用于所有浏览器!

function onReady(yourMethod) {
  var readyStateCheckInterval = setInterval(function() {
    if (document && document.readyState === 'complete') { // Or 'interactive'
      clearInterval(readyStateCheckInterval);
      yourMethod();
    }
  }, 10);
}
// use like
onReady(function() { alert('hello'); } );

它会等待额外的10毫秒才能运行,但是,这是一个更复杂的方式,不应该:

function onReady(yourMethod) {
  if (document.readyState === 'complete') { // Or also compare to 'interactive'
    setTimeout(yourMethod, 1); // Schedule to run immediately
  }
  else {
    readyStateCheckInterval = setInterval(function() {
      if (document.readyState === 'complete') { // Or also compare to 'interactive'
        clearInterval(readyStateCheckInterval);
        yourMethod();
      }
    }, 10);
  }
}

// Use like
onReady(function() { alert('hello'); } );

// Or
onReady(functionName);

另请参阅 How to check if DOM is ready without a framework?

答案 8 :(得分:2)

document.ondomcontentready=function(){}应该可以解决问题,但它没有完全的浏览器兼容性。

好像你应该只使用jQuery min