加载中...

惰性初始模式


惰性初始模式

延迟初始化 是一种允许我们延迟初始化消耗资源比较大的进程,直到需要他们的时候(才初始化)。这其中的一个例子就是jQuery的.ready()方法,它在DOM节点加载完毕之后会执行一个回调方法。

  1. $( document ).ready( function () {
  2. //ajax请求不会执行,直到DOM加载完成
  3. var jqxhr = $.ajax({
  4. url: "http://domain.com/api/",
  5. data: "display=latest&order=ascending"
  6. })
  7. .done( function( data ) ){
  8. $(".status").html( "content loaded" );
  9. console.log( "Data output:" + data );
  10. });
  11. });

jQuery.fn.ready()底层是通过byjQuery.bindReady()来实现的, 如下所示:

  1. bindReady: function() {
  2. if ( readyList ) {
  3. return;
  4. }
  5. readyList = jQuery.Callbacks( "once memory" );
  6. // Catch cases where $(document).ready() is called after the
  7. // browser event has already occurred.
  8. if ( document.readyState === "complete" ) {
  9. // Handle it asynchronously to allow scripts the opportunity to delay ready
  10. return setTimeout( jQuery.ready, 1 );
  11. }
  12. // Mozilla, Opera and webkit support this event
  13. if ( document.addEventListener ) {
  14. // Use the handy event callback
  15. document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
  16. // A fallback to window.onload, that will always work
  17. window.addEventListener( "load", jQuery.ready, false );
  18. // If IE event model is used
  19. } else if ( document.attachEvent ) {
  20. // ensure firing before onload,
  21. // maybe late but safe also for iframes
  22. document.attachEvent( "onreadystatechange", DOMContentLoaded );
  23. // A fallback to window.onload, that will always work
  24. window.attachEvent( "onload", jQuery.ready );
  25. // If IE and not a frame
  26. // continually check to see if the document is ready
  27. var toplevel = false;
  28. try {
  29. toplevel = window.frameElement == null;
  30. } catch(e) {}
  31. if ( document.documentElement.doScroll && toplevel ) {
  32. doScrollCheck();
  33. }
  34. }
  35. },

即使不直接在jQuery核心文件中使用,有些开发者通过一些插件也可能熟悉懒加载的概念,延迟加载和揽初始化一样有效,它是一种在需要的时候(比如:当用户浏览到了页面底部的时候)才加载页面数据的技术。最近几年,这种模式已经变得非常显著并且现在可以再Twitter和Facebook的UI里面zhaoda。


还没有评论.