js优化提高访问速度

1、给JS文件减肥。javascript

有的人为了给网站增长炫目效果,每每会使用一些JS效果代码,这在上个世纪彷佛还很流行,对于如今来讲,最好在用户体验确实须要的状况下,使用这些东西。至于但愿给本身的JS文件减肥的童鞋,网上的工具里有不少,在百度一搜就会有应用,功能很全。把一个已经完善的JS文件进行压缩是主流网站的一个惯性动做,由于压缩量确实很可观。如下是几个比较好的压缩工具:php

YUI压缩工具 (http://developer.yahoo.com/yui/compressor/)
Dean Edwards Packer (http://dean.edwards.name/packer/)
JSMin (http://crockford.com/JavaScript/jsmin)css

2、尽可能减小DOM访问html

使用JavaScript访问DOM元素很容易,代码更容易阅读,可是速度很慢。下面介绍几个要点:限制使用JavaScript来修饰网页布局,把针对访问元素的引用缓存起来。有时,当你的网站依赖大量的DOM改动时,就应该考虑限制你的标记。这是改用HTML五、舍弃那些原来的XHTML和HTML4的一个充分理由。前端

3、使用适当的CDNjava

如今许多网页使用内容分发网络(CDN)。它能够改进你的缓存机制,由于每一个人均可以使用它。它还能为你节省一些带宽。你很容易使用ping检测或使用Firebug调试那些服务器,以便搞清能够从哪些方面加快数据的速度。选择CDN时,要照顾到你网站那些访客的位置。记得尽量使用公共存储库。shell

4、把不着急用的JS文件放到页面的底部数组

当更多地考虑用户对网站的速度体验时,在页面底部装入JS文件是一个很是好的作法。易用性和用户放在首位,JavaScript放在末位。对于追求技术的不少前端人员来讲,这彷佛很难接受,但也应该有所准备,有些用户会禁用JavaScript。浏览器

5、在头部以异步方式装入JS缓存

为了统计网站的各类信息,咱们一般会借助网上提供的免费统计功能,好比cnzz的统计,好比google分析,好比百度统计,关键的是,好多统计为了保证统计效果,可能会建议用户将统计代码放在页面的头部。若是用户选择这么作,可能会在统计代码请求数据不稳定时给他的网站用户带来很是很差的体验。不过,目前大部分统计服务都容许你以异步方式载入放在头部的JS文件,在很大程度上解决了这一问题。

6、把你的JavaScript打包成PNG文件

这个办法是最近在网上看到老外的一种作法,思惟很特别,尚未尝试过,有兴趣的朋友能够尝试一下。具体是这样:把你的JS和CSS添加到图片的末尾,而后用CSS来裁切,经过一次HTTP请求来得到应用程序中所需的全部信息,它把你的JavaScript/css数据打包成PNG文件,而后你还能够拆包,只要使用画布API的getImageData()。这种方法效率很是高,能够在不缩小数据的状况下,多压缩35%左右。

JS动态加载JS与CSS文件

 

DEMO

一 HTML页面   jsforjscss.html

复制代码
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <script type="text/javascript" src="loadjscssfile.js"></script>
 6 <title>无标题文档</title>
 7 </head>
 8 <body>
 9 </body>
10 </html>
复制代码

二 动态加载js文件的程序   loadjscssfile.js

复制代码
// JavaScript Document
function loadjscssfile(filename,filetype){

    if(filetype == "js"){
        var fileref = document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src",filename);
    }else if(filetype == "css"){
    
        var fileref = document.createElement('link');
        fileref.setAttribute("rel","stylesheet");
        fileref.setAttribute("type","text/css");
        fileref.setAttribute("href",filename);
    }
   if(typeof fileref != "undefined"){
        document.getElementsByTagName("head")[0].appendChild(fileref);
    }
    
}
loadjscssfile("do.js","js");
loadjscssfile("test.css","css");
复制代码

三 被加载的 js文件:do.js

alert("this is do");

四 被加载的 css文件:test.css (css文件中还能够用@import url("menu.css"); 引进其余css文件)

@charset "utf-8";
@import url("menu.css");
@import url("../gundong.css");
body{
    background-color:gray;
}


 

 

理论分析:

 

原理解析:第一步:使用dom建立<script>或者<link>标签,并给他们附加属性,如type等第二步:使用appendChild方法把标签绑定到另外一个标签,通常是绑到<head>.

应用:一、提升代码的复用,减小代码量;二、添加一个javascript控制器和 session能够实现动态改变页面样式;三、因为是页面是从上到下依次加载文件的,而且边加载边解释,因此能够添加javascript控制器控制页面文件的加载顺序,如先加载css布局文件,再显示有图片的css美化文件,以后再加载大的falsh文件,或者安内容的重要性来加载。r

阅读提示:e文很差的初学者能够直接看中文,而后拷贝代码试验下。r

To load a .js or .css file dynamically, in a nutshell, it means using DOM methods to first create a swanky new "script" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together:

function loadjscssfile(filename, filetype){
if (filetype=="js"){ //断定文件类型
var fileref=document.createElement('script')//建立标签
fileref.setAttribute("type","text/javascript")//定义属性type的值为text/javascript
fileref.setAttribute("src", filename)//文件的地址
}
else if (filetype=="css"){ //断定文件类型
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}



loadjscssfile("myscript.js", "js") //打开页面时浏览器动态的加载文件
loadjscssfile("javascript.php", "js") // 打开页面时浏览器动态的加载"javascript.php" ,
loadjscssfile("mystyle.css", "css") //打开页面时浏览器动态的加载.css 文件

 

 

接下来的工做是绑定到<head>标签。绑定的时候有一个问题就是同一个文件有可能被咱们绑定两次,绑定两次浏览器也不会出现异常,可是效率就低了。为了不r

这种状况咱们能够新增一个全局数组变量,把绑定的文件名字保存在里面,每次绑定前先检查一下是否已经存在,假如存在就提示已经存在,假如不存在就绑定。r

document.getElementsByTagName("head")[0].appendChild(fileref)



By referencing the HEAD element of the page first and then calling appendChild(), this means the newly created element is added to the very end of the HEAD tag. Furthermore, you should be aware that no existing element is harmed in the adding of the new element- that is to say, if you call loadjscssfile("myscript.js", "js") twice, you now end up with two new "script" elements both pointing to the same Javascript file. This is problematic only from an efficiency standpoint, as you'll be adding redundant elements to the page and using unnecessary browser memory in the process. A simple way to prevent the same file from being added more than once is to keep track of the files added by loadjscssfile(), and only load a file if it's new:

By referencing the HEAD element of the page first and then calling appendChild(), this means the newly created element is added to the very end of the HEAD tag. Furthermore, you should be aware that no existing element is harmed in the adding of the new element- that is to say, if you call loadjscssfile("myscript.js", "js") twice, you now end up with two new "script" elements both pointing to the same Javascript file. This is problematic only from an efficiency standpoint, as you'll be adding redundant elements to the page and using unnecessary browser memory in the process. A simple way to prevent the same file from being added more than once is to keep track of the files added by loadjscssfile(), and only load a file if it's new:



Here I'm just crudely detecting to see if a file that's set to be added already exists within a list of added files' names stored in variable filesadded before deciding whether to proceed or not.Ok, moving on, sometimes the situation may require that you actually remove or replace an added .js or .css file. Lets see how that's done next.

相关文章
相关标签/搜索