开发者

how to optimize 1 large compressed JS file for different pages? (code not needed everywhere)

I have one JS-file that is merged and compressed from several separate files. So when we start our app, there is only one http request for the JS-file which makes loading it really fast for all pages.

But, a lot of the code is jquery in document.ready(). It binds events and oth开发者_如何转开发er code to elements on certain pages, but not all code is needed on all pages.

Now I was wondering if this is heavy on the browser? Or is there a way to make this more specific to only the pages the JS-code is targeting without having to split the files up again?


Your initial approach is sound. Concatenating all JS and limiting the number of server requests is a great way to optimize for front end speed.

Your next step in terms of JS performance would be:

  1. How big is your big concatenated script file? If it's relatively small, don't bother with any further optimizations. If it's huge, involving many jQuery plugins and page-specific handlers, move on:

  2. Some of the heaviest scripts out there are frameworks like jQuery, jQuery.ui, YUI, Prototype, etc. These can all be loaded from high-speed CDNs like Google CDN. This will keep your local script's file size down AND (usually) speed up the browser's fetching of the framework.

  3. Analyze the way your users navigate your site; are there any script-heavy pages or sections which are only visited by a small fraction of users? If so, moving the page-/section-specific code into a separate script just for those pages/sections can speed up the other pages.

  4. Look into the visitor profile of your site. How 'sticky' is your site? You want to look at the ratio of new visitors to returning visitors. If you have a lot of new visitors, but not a lot of returning visitors (this is the case for most small-to-medium web sites), it makes more sense to optimize for the first pageview (splitting resources into section-specific parts). If your site has a lot of returning traffic, this is less important.

  5. Remember to lazyload as many resources as you possibly can, including nonessential Javascript.

  6. One of the ways concatenated Javascripts tend to grow quickly is excessive use of jQuery plugins. In a lot of cases, the same feature or effect can be achieved with a lot less code if you create a custom function or strip down an existing plugin to the very minimal feature set.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜