zoukankan      html  css  js  c++  java
  • zepto的ready方法

    zepto中的ready函数是作为$.fn的一个方法,即作为一个zepto对象的方法

    readyRE = /complete|loaded|interactive/;
    ready: function(callback){
          // need to check if document.body exists for IE as that browser reports
          // document ready when it hasn't yet created the body element
          if (readyRE.test(document.readyState) && document.body) callback($)
          else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)
          return this
        },

    ready返回的是this,即调用ready的自身对象。

    一开始,对于采用if else语句不太了解,不清楚为什么要用两种方式调用回调函数。

    在MDN中,有这样的描述:

    document.readyState有三个值,分别为loading,interactive,completed.

    document文档正在加载时,返回"loading"。当文档结束渲染但在加载内嵌资源时,返回"interactive",并引发DOMContentLoaded事件。当文档加载完成时,返回"complete",并引发load事件.

    DomApi也提供了两个相关事件,一个是上面的DOMContentLoaded,另一个是load事件。

    所以在zepto中,必须检测document.readyState的值来判断下一步的进行的动作。

    假如我们采用的是这样的语句:

    ready: function(callback){
          // need to check if document.body exists for IE as that browser reports
          // document ready when it hasn't yet created the body element
          if (readyRE.test(document.readyState) && document.body)  document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)
          return this
        },

    那么可能出现一种情况,即document.readyState已经跳过了loading阶段,即文档已经结束渲染,并引发过DOMContentLoaded事件,那么下面的语句就不会执行。

    代码测试:

    <script type="text/javascript">
     if(document.readyState == "loading")
         document.addEventListener('DOMContentLoaded', function(){ console.log("It is OK!") }, false)
    </script>

      测试图:

    测试代码:

    if(document.readyState == "interactive" || document.readyState == "completed"  )
         document.addEventListener('DOMContentLoaded', function(){ console.log("It is OK!") }, false)

    侧视图:没有输出。

     

      

  • 相关阅读:
    json数组解析
    sparkschedule任务类
    elasticsearch的操作类
    删除hbase的region步骤和代码
    zookeeper持有者类
    zookeeper主节点竞争类
    剑指offer(61-66)编程题
    Codeforces Round #190 (Div. 2) B. Ciel and Flowers
    一些傍晚的感想
    Codeforces Round #307 (Div. 2) D. GukiZ and Binary Operations
  • 原文地址:https://www.cnblogs.com/Darlietoothpaste/p/6582676.html
Copyright © 2011-2022 走看看