zoukankan      html  css  js  c++  java
  • js优化 ----js的有序加载

    说到有序加载,我们先来说说js的无序加载:

    <script src="jquery/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
         window.onload = function () {
              $("#head").append("<script src='js/hello.js' type='text/javascript'></script>")
              $("#head").append("<script src='js/world.js' type='text/javascript'></script>");
         }
    </script>

    为什么一定要有顺序要求这个概念呢?对于上面的那个动态追加的“两个js”文件,在IE系列中,你不能保证hello.js一定会在world.js前执行,

        他只会按照服务器端返回的顺序执行代码。

     1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JsLoad.Default" %>
     2 
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     4 <html xmlns="http://www.w3.org/1999/xhtml">
     5 <head id="head">
     6     <title></title>
     7     <link href="Styles/Site.css" rel="stylesheet" type="text/css" />
     8 </head>
     9 <body>
    10     <img src="1.jpg" width="200" height="300" />
    11     <script type="text/javascript">
    12         function loadScript(url, callback) {
    13             var script = document.createElement("script");
    14             script.type = "text/javascript";
    15 
    16             //IE17             if (script.readyState) {
    18                 script.onreadystatechange = function () {
    19                     if (script.readyState == "loaded" || script.readyState == "complete") {
    20                         script.onreadystatechange = null;
    21                         callback();
    22                     }
    23                 }
    24             } else {
    25                 //非IE26                 script.onload = function () {
    27                     callback();
    28                 }
    29             }
    30             script.src = url;
    31             document.getElementById("head").appendChild(script);
    32         }
    33         //第一步加载jquery类库34         loadScript("jquery/jquery-1.4.1.js", function () {
    35             //第二步加载hello.js36             loadScript("js/hello.js", function () {
    37                 //第三步加载world.js38                 loadScript("js/world.js", function () {
    39 
    40                 });
    41             });
    42         });
    43     </script>
    44 </body>
    45 </html>

    大家也能看到,页面完全Load的时间其实也就310ms左右,大大提高了网页的下载呈现和友好型。

  • 相关阅读:
    51nod 1050 循环数组最大子段和
    51nod 1183 编辑距离
    百度之星初赛一 补题
    jquery click嵌套 事件重复注册 多次执行的问题
    Shell变量赋值语句不能有空格
    Linux得到某个文件夹内文件的个数
    Ubuntu14.04下sogou输入法的输入框只显示英文不显示中文的问题
    Eclipse中mybatis的xml文件没有提示,出现the file cannot be validated as the XML definition.....
    整理一下postgresql的扩展功能postgis和pgrouting的使用
    Windows应用程序未响应
  • 原文地址:https://www.cnblogs.com/jellychow/p/3147980.html
Copyright © 2011-2022 走看看