开发者

load different js files for different pages or load together?

I have 3 pages of site.

Page 1: 19 kb of JS

Page 2: 26 kb of JS

Page 开发者_JS百科3: 10 kb of JS

Total : 55 kb of JS

These javascript files are non repeating, means the JS needed on page 1 is not needed on page 2 and I have expiry headers set 1 month.

Still I would like to know what will be best way to load these files, should I load separate file for each page or I load these all together?


you should probably load them separately...
But, in order to speed things up you could do a trick : if you think that the user is staying for a bit (i donno, at least 5 sec) on your page, you could just load the script for that particular page and add the other ones remotely after the page loads. This way you force the client's browser to make a cache copy of your other - not needed at the moment - js files, and because they're being loaded after the dom object has been built, it doesn't slow your page rendering.
You will have to add an "addScript" function and make "addScript" calls when the document has finished loading. For the first js (for the first page) it should be something like :

function addScript(jsUrl){
    var s = document.createElement('script');
    s.setAttribute('type','text/javascript');
    s.setAttribute('src',jsUrl);
    document.getElementsByTagName('body')[0].appendChild(s);
}
window.onload = function(){
    addScript('mySecondScript.js');
    addScript('myThirdScript.js');
}
The beauty is that when you load one of the other pages, the corresponding js file is loaded instantly because it is retrieved from the browser's cache.


I'd mash them all together in one JS file, minify that with Google's Closure Compiler set on "advanced optimizations", and load it once with a bunch of cache directives. If you do use the Closure Compiler set on advanced, you'll have to make sure there is no inline JavaScript in your HTML files (which is generally not a good practice anyway), because the function and variable names (even the global functions and variable names) won't be the same afterward.


55 kb isn't all that much. However, it may be harder to update Page 2 when you have to deal with page 1 and 3 code. Also, have you tried minifying the code that sounds like rather large javascript files.


The way you described it, you should load them separately.

If the user is guaranteed to navigate to all 3 pages then yes, combine them. If they usually navigate to one page, then loading all three is a waste.

That said, 55k is not THAT large, however consider the impact from a mobile browser or even dial-up.

Minimize and use compression to reduce the JS to the maximum, but don't load a file unless it is required.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜