Home > Web Front-end > JS Tutorial > Tutorial for learning the ready method in JavaScript's jQuery library_jquery

Tutorial for learning the ready method in JavaScript's jQuery library_jquery

WBOY
Release: 2016-05-16 15:44:57
Original
1106 people have browsed it

There are many ways to learn jQuery. Today we start with jQuery’s ready function. The code in this example comes from the jQuery script library.

If you have used jQuery, you must have used the ready function, which is used to register functions that can be executed when the page is ready.

The question is, when will our page be ready?

onload event
The most basic processing method is the onload event of the page. When we handle this event, there are many ways, that is, we can write it directly in the start tag of the body element through HTML, or we can use event registration. method to use, which can be divided into DOM0 method and DOM2 method. Taking into account browser compatibility, write it in DOM2 mode, as shown below.

if (document.addEventListener) {
  // A fallback to window.onload, that will always work
  window.addEventListener("load", jQuery.ready, false);

  // If IE event model is used
} else {
  // A fallback to window.onload, that will always work
  window.attachEvent("onload", jQuery.ready);
}

Copy after login


DOMContentLoaded event
However, the onload event will not be triggered until all page elements are loaded, including images on the page, etc. If there are a large number of pictures on the web page, the effect can be imagined. The user may have started to operate the page before seeing the pictures. At this time, our page has not been initialized and the event has not been registered. Isn't this right? It's too late!

In addition to the well-known onload event, which is similar to the onload event in DOM, we also have the DOMContentLoaded event to consider. Standard-based browsers support this event. This event will be triggered when all DOM is parsed.

In this way, for standards-based browsers, we can also register the handling of this event. In this way, we may catch the loading completion event earlier.

if (document.addEventListener) {
  // Use the handy event callback
  document.addEventListener("DOMContentLoaded", DOMContentLoaded, false);

  // A fallback to window.onload, that will always work
  window.addEventListener("load", jQuery.ready, false);
}
Copy after login

onreadystatechange event
What to do with non-standard browsers?

If the browser has a document.onreadystatechange event, when the event is triggered, if document.readyState=complete, it can be considered that the DOM tree has been loaded.

However, this event is not very reliable. For example, when there are images in the page, it may not be triggered until after the onload event. In other words, it can only be executed correctly when the page contains no binary resources or very few or is cached. As an alternative.

if (document.addEventListener) {
  // Use the handy event callback
  document.addEventListener("DOMContentLoaded", DOMContentLoaded, false);

  // A fallback to window.onload, that will always work
  window.addEventListener("load", jQuery.ready, false);

  // If IE event model is used
} else {
  // Ensure firing before onload, maybe late but safe also for iframes
  document.attachEvent("onreadystatechange", DOMContentLoaded);

  // A fallback to window.onload, that will always work
  window.attachEvent("onload", jQuery.ready);
}

Copy after login

What is the DOMContentLoaded function doing? Finally, the jQuery.ready function needs to be called.

DOMContentLoaded = function() {
  if ( document.addEventListener ) {
    document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
    jQuery.ready();
  } else if ( document.readyState === "complete" ) {
    // we're here because readyState === "complete" in oldIE
    // which is good enough for us to call the dom ready!
    document.detachEvent( "onreadystatechange", DOMContentLoaded );
    jQuery.ready();
  }
} 
Copy after login
doScroll detection method
MSDN has an inconspicuous saying about a JScript method. When the page DOM is not loaded, an exception will be generated when the doScroll method is called. Then we use it in reverse. If there is no exception, then the page DOM has been loaded!

Diego Perini in 2007 reported a way to detect whether IE is loaded, using the doScroll method call. Detailed instructions can be found here.
The principle is that when IE is in a non-iframe, it can only continuously judge whether the DOM is loaded by whether it can execute doScroll. In this example, try to execute doScroll every 50 milliseconds. Note that calling doScroll will cause an exception when the page is not loaded, so try -catch is used to catch the exception.

(function doScrollCheck() {
  if (!jQuery.isReady) {

    try {
      // Use the trick by Diego Perini
      // http://javascript.nwbox.com/IEContentLoaded/
      top.doScroll("left");
    } catch (e) {
      return setTimeout(doScrollCheck, 50);
    }

    // and execute any waiting functions
    jQuery.ready();
  }
})();

Copy after login

document.readyState 状态
如果我们注册 ready 函数的时间点太晚了,页面已经加载完成之后,我们才注册自己的 ready 函数,那就用不着上面的层层检查了,直接看看当前页面的 readyState 就可以了,如果已经是 complete ,那就可以直接执行我们准备注册的 ready 函数了。不过 ChrisS 报告了一个很特别的错误情况,我们需要延迟一下执行。

setTimeout 经常被用来做网页上的定时器,允许为它指定一个毫秒数作为间隔执行的时间。当被启动的程序需要在非常短的时间内运行,我们就会给她指定一个很小的时间数,或者需要马上执行的话,我们甚至把这个毫秒数设置为0,但事实上,setTimeout有一个最小执行时间,当指定的时间小于该时间时,浏览器会用最小允许的时间作为setTimeout的时间间隔,也就是说即使我们把setTimeout的毫秒数设置为0,被调用的程序也没有马上启动。

这个最小的时间间隔是多少呢?这和浏览器及操作系统有关。在John Resig的新书《Javascript忍者的秘密》一书中提到

Browsers all have a 10ms minimum delay on OSX and a(approximately) 15ms delay on Windows.(在苹果机上的最小时间间隔是10毫秒,在Windows系统上的最小时间间隔大约是15毫秒)

,另外,MDC中关于setTimeout的介绍中也提到,Firefox中定义的最小时间间隔(DOM_MIN_TIMEOUT_VALUE)是10毫秒,HTML5定义的最小时间间隔是4毫秒。既然规范都是这样写的,那看来使用setTimeout是没办法再把这个最小时间间隔缩短了。

这样,通过设置为 1, 我们可以让程序在浏览器支持的最小时间间隔之后执行了。

// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if (document.readyState === "complete") {
  // 延迟 1 毫秒之后,执行 ready 函数
  setTimeout(jQuery.ready, 1);
} 
Copy after login


完整的代码
在 jQuery 中完整的代码如下所示。位于 jQuery 1.8.3 源代码的 #842 行。

jQuery.ready.promise = function( obj ) {
  if ( !readyList ) {

    readyList = jQuery.Deferred();

    // Catch cases where $(document).ready() is called after the browser event has already occurred.
    // we once tried to use readyState "interactive" here, but it caused issues like the one
    // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
    if ( document.readyState === "complete" ) {
      // Handle it asynchronously to allow scripts the opportunity to delay ready
      setTimeout( jQuery.ready, 1 );

    // Standards-based browsers support DOMContentLoaded
    } else if ( document.addEventListener ) {
      // Use the handy event callback
      document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

      // A fallback to window.onload, that will always work
      window.addEventListener( "load", jQuery.ready, false );

    // If IE event model is used
    } else {
      // Ensure firing before onload, maybe late but safe also for iframes
      document.attachEvent( "onreadystatechange", DOMContentLoaded );

      // A fallback to window.onload, that will always work
      window.attachEvent( "onload", jQuery.ready );

      // If IE and not a frame
      // continually check to see if the document is ready
      var top = false;

      try {
        top = window.frameElement == null && document.documentElement;
      } catch(e) {}

      if ( top && top.doScroll ) {
        (function doScrollCheck() {
          if ( !jQuery.isReady ) {

            try {
              // Use the trick by Diego Perini
              // http://javascript.nwbox.com/IEContentLoaded/
              top.doScroll("left");
            } catch(e) {
              return setTimeout( doScrollCheck, 50 );
            }

            // and execute any waiting functions
            jQuery.ready();
          }
        })();
      }
    }
  }
  return readyList.promise( obj );
};

Copy after login

那么,又是谁来调用呢?当然是需要的时候,在我们调用 ready 函数的时候,才需要注册这些判断页面是否完全加载的处理,这段代码在 1.8.3 中位于代码的 #244 行,如下所示:

ready: function( fn ) {
  // Add the callback
  jQuery.ready.promise().done( fn );

  return this;
}

Copy after login

在页面上引用 jQuery 脚本库之后,执行了 jQuery 的初始化函数,初始化函数中创建了 ready 函数。我们在通过 ready 函数注册事件处理之前,jQuery 完成了页面检测代码的注册。这样。当页面完全加载之后,我们注册的函数就被调用了。


jQuery Ready 方法的简短写法

写 jQuery 代码的时候,一般要写一个 Ready 方法,以确保 DOM 已加载完毕,然后再执行相应的 jQuery 代码。Ready 方法一般写法如下:

$(document).ready(function() {
  // 从这里开始
});

Copy after login

但是在看其他人写的 jQuery 代码的时候,经常又会看到如下写法:

$(function() {
  // 从这里开始
});

Copy after login

第二种写法虽然简短了许多,但是在功能上和第一种写法是等价的,如果你不相信,可以看一下 jQuery 的源代码中有如下代码片段:

// HANDLE: $(function)
// Shortcut for document ready 
if ( jQuery.isFunction( selector ) ) {
  return rootjQuery.ready( selector );
}

Copy after login

如果传入选择器中的参数是一个函数,那么会自动返回一个 rootjQuery.ready( selector ),而 rootjQuery 又是 jQuery(document) 的一个引用,所以这里就相当于调用 jQuery(document).ready() 方法,而之前的那个匿名方法亦被传入其中以备执行。

这种简短写法虽说减少了了一点代码量,但是可读性稍差,所以我个人还是倾向于前面的第一种写法,特别是在团队开发中,仅仅是为了语意明确。


 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template