Pure équivalent JavaScript de jQuery paramètre#39;s $.ready() - comment appeler une fonction lorsque la page/DOM est prête pour elle

Mots clés : javascriptjqueryhtmljavascript

meilleur 5 Réponses Pure équivalent JavaScript de jQuery paramètre#39;s $.ready() - comment appeler une fonction lorsque la page/DOM est prête pour elle

vote vote

91

<!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> 
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 }); 
document.addEventListener('DOMContentLoaded', fn, false); 
window.addEventListener('load', fn, false ) 
document.attachEvent("onreadystatechange", fn); 
window.attachEvent("onload", fn); 
(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); 
// 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 
vote vote

89

document.addEventListener("DOMContentLoaded", function(event) {     // Your code to run since DOM is loaded and ready }); 
$(document).ready(function() {     console.log("Ready!"); }); 
$(function() {     console.log("ready!"); }); 
 Example:  (function() {    // Your page initialization code here  - WRONG    // The DOM will be available here   - WRONG })(); 
vote vote

75

// 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!'); }); 
vote vote

70

document.onreadystatechange = function () {   var state = document.readyState;   if (state == 'interactive') {       init();   } else if (state == 'complete') {       initOnCompleteLoad();   } }​; 
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 }); 
vote vote

56

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'); }); 

Questions similaires