2014-01-09 52 views
1

我正在尋找jQuery的document.ready()的原生JavaScript解決方案。看看this thread,CMS建議只使用jQuery用來實現其document.ready()的code。我正在尋找bindReady(),但我不確定如何將其納入我的代碼。我現在有一些諸如:本機JavaScript document.ready - 如何使用bindReady()

$(document).ready(function() { 
    console.log('foo'); 
}); 
+1

你可以試試'window.onload = function(){}',這可能對你來說已經足夠了。 –

+0

@RocketHazmat根據我的理解,只有在所有元素(包括圖像)加載完成後,纔會觸發'window.onload'。 '$(document).ready()'僅在HTML加載完成時觸發。由於我的頁面上有很多大圖片,因此我不希望我的用戶在運行腳本之前等待加載圖像。 – Jon

回答

2

基本上當你需要做的是替換具有

jQuery.ready(); 

與要調用的函數的名稱線。如果你想要的東西像jQuery的ready註冊方法一樣工作,建立一個產生隊列的函數。當「就緒」被觸發時,循環通過隊列。


您需要了解更多信息,以下是一個不使用超時的快速而髒的示例。這不是生產準備,只是一個基本的POC。

(function() { 

     var ready = { 
      _readyQueue: [], 
      _hasRun: false, 
      _docReadyCalled : function() { 
       this._hasRun = true; 
       this._execute(); 
      }, 
      _execute: function() { 
       var func; 
       while (this._readyQueue.length) { 
        func = this._readyQueue.shift(); 
        func(); 
       } 
      }, 
      register: function (func) { 
       this._readyQueue.push(func); 
       if (this._hasRun) { 
        this._execute(); 
       } 
      }   
     } 

     window.docReady = ready.register.bind(ready); //use what ever global namespace you want here 

     function bindReady() { 

      /* This would be that jQuery code, I am just use window load here so not so much code */ 

      //Not all browser support this, quick and dirty for example 
      window.addEventListener('load', ready._docReadyCalled.bind(ready), false); 

     } 

     bindReady(); 

    })(); 


    /* waiting for DOM to be ready */ 
    docReady(function() { console.log("here"); }); 
    docReady(function() { console.log("there"); }); 

    /* Showing what happens when you call docReady after it is ready */ 
    docReady(function() { console.log("registering ready again"); docReady(function() { console.log("I am here!"); }); }); 
+0

對不起,我不太理解。你能用一個例子來解釋嗎? – Jon

+0

你需要解釋什麼?替換'jQuery.ready();'行或建立一個簡單的隊列。 :) – epascarello

+0

所以在我的例子中,我會這樣做:'function foo(){console.log('foo'); }'?然後我會用'setInterval()'建立一個隊列,它會持續檢查'$(document).ready()'是否準備好了? – Jon

0

最好的辦法是可能完全避免使用DOM事件。當你想盡早加載時,它變得非常複雜但是想要確定它不是太早提前。這是一個容易和100%可靠的技術儘快的DOM完成加載執行代碼:

<html> 
<head> 
    <!-- head content, blah, blah, blah --> 
    <script> 
     var ready = function() { 
      // Put everything in this function that you want to run when the page loads 
      nowTheDomIsLoaded(); 
      console.log('foo'); 
     }; 
    </script> 
</head> 
<body> 
    <!-- page content, blah, blah, blah --> 
    <script>ready();</script> 
</body> 
</html> 

基本上你把你想要運行的一切功能(如ready())和你之前做的最後一件事關閉</body>標籤是你執行該功能。由於<body>中的所有內容都已被解析,所以您知道DOM已加載,並且不需要任何特殊的庫。