What is the best method to reduce the size of my J

2019-01-07 11:09发布

When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?

18条回答
唯我独甜
2楼-- · 2019-01-07 11:19

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.

查看更多
小情绪 Triste *
3楼-- · 2019-01-07 11:19

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.

查看更多
霸刀☆藐视天下
4楼-- · 2019-01-07 11:21

Helping the YUI Compressor gives some good advice on how you can tweak your scripts to achieve even better savings.

查看更多
唯我独甜
5楼-- · 2019-01-07 11:22

Compression and minify-ing (removing whitespace) are a start.

Additionally:

  1. 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.

  2. 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" />

查看更多
看我几分像从前
6楼-- · 2019-01-07 11:23

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)

查看更多
爷、活的狠高调
7楼-- · 2019-01-07 11:26

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:

background: #fff url(image.gif) no-repeat top left;

...instead of:

background-color: #fff;
background-image: url(image.gif);
background-repeat: no-repeat;
background-position: top left;

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:

body{font-family:arial;}

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

<script type="text/javascript" src="/scripts/loginChecker.js"></script>

Including CSS

<link rel="stylesheet" href="/css/myStyle.css" type="text/css" media="All" />
查看更多
登录 后发表回答