When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Shrinksafe may help: http://shrinksafe.dojotoolkit.org/ We're using it and it does a pretty good job. We execute it from an ant build for when packaging our web app.
Try web compressor tools from Boryi to compress your standard HTML file (without Javascript code and css code embedded, but can be linked to or imported), Javascript code (properly ended with ;), and css code.
Helping the YUI Compressor gives some good advice on how you can tweak your scripts to achieve even better savings.
Compression and minify-ing (removing whitespace) are a start.
Additionally:
Combine all of your JavaScript and CSS includes into a single file. That way the browser can download the source in a single request to server. Make this part of your build process.
Turn caching on at the web-server level using the cache-control http header. Set the expiry to a large value (like a year) so the browser will only download the source once. To allow for future edits, include a version number on the query-string, like this:
<script src="my_js_file.js?1.2.0.1" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="my_css_file.css?3.1.0.926" />
See the question: Best javascript compressor
Depending on whether or not you are going to gzip your JavaScript files may change your choice of compressor. (Currently Packer isn't the best choice if you are also going to gzip, but see the above question for the current best answer)
In addition to using server side compression, using intelligent coding is the best way to keep bandwidth costs low. You can always use tools like Dean Edward's Javascript Packer, but for CSS, take the time to learn CSS Shorthand. E.g. use:
...instead of:
Also, use the cascading nature of CSS. For example, if you know that your site will use one font-family, define that for all elements that are in the body tag like this:
One other thing that can help is including your CSS and JavaScript as files instead of inline or at the head of each page. That way your server only has to serve them once to the browser after that browser will go from cache.
Including Javascript
Including CSS