JavaScript 惰性初始模式

2018-08-02 16:27 更新

惰性初始模式

延遲初始化 是一種允許我們延遲初始化消耗資源比較大的進程,直到需要他們的時候(才初始化)。這其中的一個例子就是jQuery的.ready()方法,它在DOM節(jié)點加載完畢之后會執(zhí)行一個回調(diào)方法。

$( document ).ready( function () {

    //ajax請求不會執(zhí)行,直到DOM加載完成

    var jqxhr = $.ajax({
      url: "http://domain.com/api/",
      data: "display=latest&order=ascending"
    })
    .done( function( data ) ){
        $(".status").html( "content loaded" );
        console.log( "Data output:" + data );
    });

});

jQuery.fn.ready()底層是通過byjQuery.bindReady()來實現(xiàn)的, 如下所示:

bindReady: function() {
  if ( readyList ) {
    return;
  }

  readyList = jQuery.Callbacks( "once memory" );

  // Catch cases where $(document).ready() is called after the
  // browser event has already occurred.
  if ( document.readyState === "complete" ) {
    // Handle it asynchronously to allow scripts the opportunity to delay ready
    return setTimeout( jQuery.ready, 1 );
  }

  // Mozilla, Opera and webkit support this event
  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 if ( document.attachEvent ) {
    // 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 toplevel = false;

    try {
      toplevel = window.frameElement == null;
    } catch(e) {}

    if ( document.documentElement.doScroll && toplevel ) {
      doScrollCheck();
    }
  }
},

即使不直接在jQuery核心文件中使用,有些開發(fā)者通過一些插件也可能熟悉懶加載的概念,延遲加載和攬初始化一樣有效,它是一種在需要的時候(比如:當用戶瀏覽到了頁面底部的時候)才加載頁面數(shù)據(jù)的技術(shù)。最近幾年,這種模式已經(jīng)變得非常顯著并且現(xiàn)在可以再Twitter和Facebook的UI里面zhaoda。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號