开发者

javascript parallel loading

I heard that javascripts files on web pages were not downloaded parallelly, so I did some experiment on firefox using firebugs. However, I did see javascripts were donwloaded in parallel, and my web page included sripts in old fasion way:

<head>
    <meta charset="utf-8" />
    <title>Home Page</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script开发者_运维百科>
</head>

Since the article I read was written in 2009, I am wondering if anything changed after, or did firefox did the javascripts loading in different way??

Thanks


Browsers will download resources (images, scripts, frames, etc...) in parallel (up to some max number of them concurrently), but some resources such as script resources are not safe to be parsed and executed in parallel because they may have been written to execute in a particular order.

So, while the browser can load script tags in parallel, it waits until it can execute them in sequence (assuming they are normal inline script tags without any special attributes like "defer" or "async"). But, even in those cases (except for webworkers which isn't what is being discussed here), javascript is single threaded so only one piece of javascript will execute at a time.


It's not about the downloading, but about the parsing and executing. If the second Javascript file depends on some global variable set in the first Javascript file, then it cannot be executed and not even fully parsed before the first one is loaded. Since there is no easy way for a Browser do determine if there are such dependencies, the safe way is to parse and execute the files sequentially.

Since there is the possibility to do document.write() commands and to generally alter the DOM, while the Javscript is parsed and executed, parsing and rendering of the HTML has to wait, too.

There are hacks such as this that will dynamically add a new script definition, which is loaded and parsed in parallel. More elegant is the defer attribute, but the browsers do not all handle it the same.


Usually scripts are not loaded in parallel, since sometimes loading order is important.

The script elements block progressive page downloads. Browsers download several components at a time, but when they encounter an external script, they stop further downloads until the script file is downloaded, parsed, and executed.

However, there are ways to allow downloading of scripts in parallel:

As a side note, there are some common attributes developers tend to use with the <script> element: [...]

  • defer (And better yet, HTML5’s async) is also a way, albeit not widely supported, to specify that downloading the external script file shouldn’t block the rest of the page.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜