gomymobi.com - Free Business Site Builder & Platform

Cách tốt nhất để nạp các tệp JavaScript Để nạp nội dung của một tệp JavaScript dĩ nhiên chúng ta có rất nhiều cách, tuy nhiên bạn có biết được cách nào để là tối ưu và tốt nhất? Nếu chưa thì bạn hãy đọc bài viết này, tác giả sẽ chỉ ra nguyên nhân và cách giải quyết tốt nhất cho vấn đề này.

Not too long ago, I wrote about loading JavaScript without blocking by creating a dynamic <script> tag. When <script> tags are in the flow of an HTML document, the browser must stop rendering and wait for the script file to download and execute before continuing (example). Creating a new <script> tag via JavaScript avoids this issue because it's out of the flow of the document, so the script file is downloaded and executed without waiting. The result: dynamically loading JavaScript files allows your page to render faster and therefore improve perceived performance.

The best technique

Steve Souders has explored several different ways to load JavaScript without blocking both on his blog and in his books. After thinking about it and experimenting, I've come to the conclusion that there's just one best practice for loading JavaScript without blocking:

  1. Create two JavaScript files. The first contains just the code necessary to load JavaScript dynamically, the second contains everything else that's necessary for the initial level of interactivity on the page.
  2. Include the first JavaScript file with a <script> tag at the bottom of the page, just inside the </body>.
  3. Create a second <script> tag that calls the function to load the second JavaScript file and contains any additional initialization code.

That's it! There's really no need to do anything else. The key takeaway is to have only two JavaScript and make the first one as small as possible. For example, the first file may just contain this function:

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
    } else {  //Others
        script.onload = function(){

    script.src = url;

That's a tiny amount of code to get your bootstrapped so it will load incredibly fast (especially when gzipped).

The actual code on your page ends up looking like this:

<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
    //initialization code

The key to this whole technique is to have just two JavaScript files, so the second one contains everything that's needed to initialize the page. What if your page requires more than two files? Then you should be concatenating your files together either at build time (using something like Sprockets) or at run time (using something like mod_concat or a combo handler). There should never be a time when your page requires more than these two JavaScript files to properly initialize. Each additional HTTP request has overhead, and then you'll need to worry about sequencing the downloads so code is executed in the correct order. By having just two files, you eliminate a large point of concern over which file is downloaded and executed first as well as eliminating unnecessary HTTP requests.

YUI 3 has you covered

YUI 3 is designed around this very premise. You can start by just loading the yui.js file and then use the built-in Loader component to dynamically load the rest of the YUI library. For example:

<script src="http://yui.yahooapis.com/3.0.0b1/build/yui/yui-min.js" type="text/javascript"></script>
<script type="text/javascript">
YUI().use("node", function(Y){
    //initialization code

This code loads in the YUI "seed" file first, then creates a new instance of the YUI object and indicates that the "node" component is necessary. Behind the scenes, YUI constructs a URL with all of the dependencies for "node", dynamically loads it, then calls the callback function when complete. The cool thing about the YUI 3 approach is that you don't need to worry about including the URL for the JavaScript statically, just indicate which components you need and the library figures out the correct URL to download (details).


Though there's been a lot of research on ways to load JavaScript without blocking, there really is just one way that I'd recommend as a best practice. There should really be no need to load anything more than two scripts to get your site initialize and interactive. Make the initial JavaScript file as small as possible and then load in the larger one dynamically to avoid blocking. This is the simplest, easiest way to get all of your JavaScript onto the page without affecting the user experience.

Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of Yahoo!, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.

JavaScript theo ngày

Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web