来自国外的页面JavaScript文件优化

The problem: scripts block downloads


Let's first take a look at what the problem is with the script downloads. The thing is that before fully downloading and parsing a script, the browser can't tell what's in it. It may contain document.write() calls which modify the DOM tree or it may even contain location.href and send the user to a whole new page. If that happens, any components downloaded from the previous page may never be needed. In order to avoid potentially useless downloads, browsers first download, parse and execute each script before moving on with the queue of other components waiting to be downloaded. As a result, any script on your page blocks the download process and that has a negative impact on your page loading speed.

Here's how the timeline looks like when downloading a slow JavaScript file (exaggerated to take 1 second). The script download (the third row in the image) blocks the two-by-two parallel downloads of the images that follow after the script:

Here's the example to test yourself.

Problem 2: number of downloads per hostname

Another thing to note in the timeline above is how the images following the script are downloaded two-by-two. This is because of the restriction of how many components can be downloaded in parallel. In IE <= 7 and Firefox 2, it's two components at a time (following the HTTP 1.1 specs), but both IE8 and FF3 increase the default to 6.

You can work around this limitation by using multiple domains to host your components, because the restriction is two components per hostname. For more information of this topic check the article “Maximizing Parallel Downloads in the Carpool Lane” by Tenni Theurer.

The important thing to note is that JavaScripts block downloads across all hostnames. In fact, in the example timeline above, the script is hosted on a different domain than the images, but it still blocks them.

Scripts at the bottom to improve user experience

As Yahoo!'s Performance rules advise, you should put the scripts at the bottom of the page, towards the closing </body> tag. This doesn't really make the page load faster (the script still has to load), but helps with the progressive rendering of the page. The user perception is that the page is faster when they can see a visual feedback that there is progress.

Non-blocking scripts

It turns out that there is an easy solution to the download blocking problem: include scripts dynamically via DOM methods. How do you do that? Simply create a new <script> element and append it to the <head>:

var js = document.createElement('script');

js.src = 'myscript.js';

var head = document.getElementsByTagName('head')[0];

head.appendChild(js);

Here's the same test from above, modified to use the script node technique. Note that the third row in the image takes just as long to download, but the other resources on the page are loading simultaneously:

Test example

As you can see the script file no longer blocks the downloads and the browser starts fetching the other components in parallel. And the overall response time is cut in half.

Dependencies

A problem with including scripts dynamically would be satisfying the dependencies. Imagine you're downloading 3 scripts and three.js requires a function from one.js. How do you make sure this works?

Well, the simplest thing is to have only one file, this way not only avoiding the problem, but also improving performance by minimizing the number of HTTP requests (performance rule #1).

If you do need several files though, you can attach a listener to the script's onload event (this will work in Firefox) and the onreadystatechange event (this will work in IE). Here's a blog post that shows you how to do this. To be fully cross-browser compliant, you can do something else instead: just include a variable at the bottom of every script, as to signal “I'm ready”. This variable may very well be an array with elements for every script already included.

Using YUI Get utility

The YUI Get Utility makes it easy for you to use script includes. For example if you want to load 3 files, one.js, two.js and three.js, you can simply do:

var urls = ['one.js', 'two.js', 'three.js'];

YAHOO.util.Get.script(urls);

YUI Get also helps you with satisfying dependencies, by loading the scripts in order and also by letting you pass an onSuccess callback function which is executed when the last script is done loading. Similarly, you can pass an onFailure function to handle cases where scripts fail to load.

var myHandler = {

onSuccess: function(){

alert(':))');

},

onFailure: function(){

alert(':((');

}

};

var urls = ['1.js', '2.js', '3.js'];

YAHOO.util.Get.script(urls, myHandler);

Again, note that YUI Get will request the scripts in sequence, one after the other. This way you don't download all the scripts in parallel, but still, the good part is that the scripts are not blocking the rest of the images and the other components on the page. Here's a good example and tutorial on using YUI Get to load scripts.

YUI Get can also include stylesheets dynamically through the method YAHOO.util.Get.css() [example].

Which brings us to the next question:

And what about stylesheets?

Stylesheets don't block downloads in IE, but they do in Firefox. Applying the same technique of dynamic inserts solves the problem. You can create dynamic link tags like this:

var h = document.getElementsByTagName('head')[0];

var link = document.createElement('link');

link.href = 'mycss.css';

link.type = 'text/css';

link.rel = 'stylesheet';

h.appendChild(link);

This will improve the loading time in Firefox significantly, while not affecting the loading time in IE.

Another positive side effect of the dynamic stylesheets (in FF) is that it helps with the progressive rendering. Usually both browsers will wait and show blank screen until the very last piece of stylesheet information is downloaded, and only then they'll start rendering. This behavior saves them the potential work of re-rendering when new stylesheet rules come down the wire. With dynamic <link>s this is not happening in Firefox, it will render without waiting for all the styles and then re-render once they arrive. IE will behave as usual and wait.

But before you go ahead and implement dynamic <link> tags, consider the violation of the rule of separation of concerns: your page formatting (CSS) will be dependent on behavior (JS). In addition, this problem is going to be addressed in future Firefox versions.

Other ways?

There are other ways to achieve the non-blocking scripts behavior, but they all have their drawbacks.




















Method Drawback
Using defer attribute of the script tag IE-only, unreliable even there
Using document.write() to write a script tag
  1. Non-blocking behavior is in IE-only
  2. document.write is not a recommended coding practice
XMLHttpRequest to get the source then execute with eval().
  1. eval() is evil”
  2. same-domain policy restriction
XHR request to get the source, create a new script tag and set its content
  1. more complex
  2. same-domain policy
Load script in an iframe
  1. complex
  2. iframe overhead
  3. same-domain policy

Future

Safari and IE8 are already changing the way scripts are getting loaded. Their idea is to download the scripts in parallel, but execute them in the sequence they're found on the page. It's likely that one day this blocking problem will become negligible, because only a few users will be using IE7 or lower and FF3 or lower. Until then, a dynamic script tag is an easy way around the problem.

Summary


  • Scripts block downloads in FF and IE browsers and this makes your pages load slower.
  • An easy solution is to use dynamic <script> tags and prevent blocking.
  • YUI Get Utility makes it easier to do script and style includes and manage dependencies.
  • You can use dynamic <link> tags too, but consider the separation of concerns first.

(0)

相关推荐

  • 来自国外的页面JavaScript文件优化

    The problem: scripts block downloads Let's first take a look at what the problem is with the script downloads. The thing is that before fully downloading and parsing a script, the browser can't tell what's in it. It may contain document.write() calls

  • JavaScript 文件加载与阻塞问题之性能优化案例详解

    上来先给一个问题:在书写html页面时,当你要从外部引入js文件时,script标签会放置在哪个位置呢,放置位置不同对页面加载有影响吗? 默认情况下,浏览器是同步加载 JavaScript 脚本:即渲染引擎遇到 script 标签就会停下来,等到执行完脚本,再继续向下渲染.如果是外部脚本,还必须加入脚本下载的时间. 如果脚本体积很大,下载和执行的时间就会很长,因此造成浏览器堵塞,用户会感觉到浏览器"卡死",出现短暂的空白,没有任何响应.这会造成很不好的用户体验,解决这个问题有两种方案:

  • 详解vue-cli + webpack 多页面实例配置优化方法

    本文介绍了vue-cli + webpack 多页面实例配置优化方法,分享给大家 vue+webpack是否有多页面 目前使用vue来做项目,估计大部分都是单页面(SPA)应用,一个轻型的 MVVM 框架,谁用了MVVM框架,就再也回不去JQ时代了,哈哈. 在手机端的项目,使用vue + vue-router是high到爆,不仅仅是我们开发的而言,最主要的用户体检也是开足马力,体检感杠杠的. 那问题来了,使用vue+webpack的单页面是爽到爆,那如果是多页面也能不能high到爆呢?那当然呀,

  • 利用r.js打包模块化的javascript文件方法示例

    前言 r.js(本地下载)是requireJS的优化(Optimizer)工具,可以实现前端文件的压缩与合并,在requireJS异步按需加载的基础上进一步提供前端优化,减小前端文件大小.减少对服务器的文件请求.本文将详细介绍r.js的相关内容,感兴趣的朋友们下面来一起看看吧. 简单打包 [项目结构] 以一个简单的例子来说明r.js的使用.该项目名称为'demo',在js目录下包含s1.js和s2.js两个文件,使用requirejs进行模块化,内容如下 //s1.js define(funct

  • JavaScript性能优化总结之加载与执行

    前言 无论当前 JavaScript 代码是内嵌还是在外链文件中,页面的下载和渲染都必须停下来等待脚本执行完成.JavaScript 执行过程耗时越久,浏览器等待响应用户输入的时间就越长.浏览器在下载和执行脚本时出现阻塞的原因在于,脚本可能会改变页面或 JavaScript 的命名空间,它们对后面页面内容造成影响.一个典型的例子就是在页面中使用document.write(),例如清单 1 清单 1 JavaScript 代码内嵌示例 <html> <head> <title

  • 基于JavaScript 性能优化技巧心得(分享)

    JavaScript 作为当前最为常见的直译式脚本语言,已经广泛应用于 Web 应用开发中.为了提高Web应用的性能,从 JavaScript 的性能优化方向入手,会是一个很好的选择. 本文从加载.上下文.解析.编译.执行和捆绑等多个方面来讲解 JavaScript 的性能优化技巧,以便让更多的前端开发人员掌握这方面知识. 什么是高性能的 JavaScript 代码? 尽管目前没有高性能代码的绝对定义,但却存在一个以用户为中心的性能模型,可以用作参考:RAIL模型. 响应 如果你的应用程序能在1

  • Javascript前端优化代码

    if 判断的优化 JavaScript条件语句在我们平时的开发中是不可避免要用到的,但是很多时候我们的代码写的并不好,一连串的if-else或者多重嵌套判断都会使得代码很臃肿,下面举例进行优化. 需求:现在有 4 个产品,分别是手机.电脑.电视机.游戏机,当然每个产品显示的价格不一样. 1.最简单的方法:if 判断 let commodity = { phone: '手机', computer: '电脑', television: '电视', gameBoy: '游戏机', } function

  • 理解Javascript文件动态加载

    Javascript文件动态加载一直是比较困扰的一件事情,像网络上传的比较常见的做法: function loadjs(fileurl){ var sct = document.createElement("script"); sct.src = fileurl; document.head.appendChild(sct); } 然后我们来测试一下结果: <html> <head> <link rel="stylesheet" typ

  • javascript性能优化之事件委托实例详解

    本文实例分析了javascript性能优化之事件委托.分享给大家供大家参考,具体如下: 为下面每个LI绑定一个click事件 <ul id="myLinks"> <li id="goSomewhere" >Go somewhere</li> <li id="doSomething" >Do something</li> <li id="sayHi" >Sa

  • 动态加载JavaScript文件的两种方法

    这篇文章主要为大家详细介绍了动态加载JavaScript文件的两种方法,感兴趣的小伙伴们可以参考一下 第一种便是利用ajax方式,把script文件代码从背景加载到前台,而后对加载到的内容经过eval()实施代码.第二种是,动静创建一个script标签,配置其src属性,经过把script标签插入到页面head来加载js,相当于正在head中写了一个<script src="..."></script>,只可是这个script标签是用js动静创建的 比喻说是我们

随机推荐