用LazyLoad实现Javascript脚本与Css样式文件延迟加载

        为了防止Javascript脚本block住浏览器进程. 往往我们需要等整个Page加载后再加载Javascript脚本.可以使用LazyLoad library.在经过最小化压缩后只有966字节.LazyLoad将从你指定URL文件数组自动并行加载并且确保执行顺序.  例如常规加载2个JS文件,1个CSS文件:

   1:  <link rel="stylesheet" href="http://www.asp.net/ajaxlibrary/Themes/Ajax/AspNetSiteStyles.css" type="text/css" />
   2:  <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
   3:  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js" ></script>
   4:  <script type="text/javascript">
   5:      $(document).ready(function() {
   6:    $("img").slideUp(1000);    
   7:  })
   8:  </script>

使用LazyLoad加载多个JS文件以及CSS文件,看下面代码片断:

   1:     LazyLoad.js(['http://code.jquery.com/jquery-1.6.4.min.js', 'http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js'], function () {
   2:           alert('jquery-1.6.4.min.js and jquery-ui.min.js have been loaded');    
   3:            $("img").slideUp(1000);
   4:          });
   5:     
   6:     // Load a CSS file and pass an argument to the callback function.
   7:     LazyLoad.css('http://www.asp.net/ajaxlibrary/Themes/Ajax/AspNetSiteStyles.css', function (arg) {
   8:          alert(arg);
   9:      }, 'AspNetSiteStyles.css has been loaded');

在Firebug中加载顺序及时间轴如下图:

FirebugTimeLine

再看动态生成的HTML:

LazyloadJsCss

我们DEMO示例中BODY标签中的HTML是这样的,试图在动态加载JQuery库后对IMG标签做一个动画操作.

   1:      <h2>
   2:          Author: Petter Liu   
   3:          <a href="http://www.cnblogs.com/wintersun" target="_blank">http://www.cnblogs.com/wintersun</a>
   4:      </h2>
   5:      <img src="http://en.academic.ru/pictures/enwiki/67/Carson_city_nevada_capitol.jpg" alt="city" />

很简单,用纯Javascript来实现核心的方法动态加载是类似这样的:

   1:      window.onload = downloadComponents;
   2:      // Download external components dynamically using JavaScript.
   3:      function downloadComponents() {
   4:          downloadJS("http://code.jquery.com/jquery-1.6.4.min.js");
   5:          downloadCSS("http://www.asp.net/ajaxlibrary/Themes/Ajax/AspNetSiteStyles.css");
   6:      }
   7:      // Download a script dynamically.
   8:      function downloadJS(url) {
   9:          var elem = document.createElement("script");
  10:          elem.src = url;
  11:          document.body.appendChild(elem);
  12:      }
  13:      // Download a stylesheet dynamically.
  14:      function downloadCSS(url) {
  15:          var elem = document.createElement("link");
  16:          elem.rel = "stylesheet";
  17:          elem.type = "text/css";
  18:          elem.href = url;
  19:          document.body.appendChild(elem);
  20:      }

希望这篇文章对您Web开发有帮助.


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

你可能感兴趣的:(JavaScript)