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左右,大大提高了网页的下载呈现和友好型。

  • 相关阅读:
    JavaScript 操作CSS
    源码搭建LAMP服务器
    Modified 2 color sort
    python的网络库
    找出有序整数数组中下标与值相同的所有元素
    sql 查看Oralce 数据库连接状态
    oracle 快闪 sql
    Sql server dblink
    昆山桶装水/免费送货上门/
    C# Tostring() 格式大全 [转]
  • 原文地址:https://www.cnblogs.com/jellychow/p/3147980.html
Copyright © 2011-2022 走看看