What is the best method to reduce the size of my Javascript and CSS files?

安稳与你 提交于 2019-11-26 10:58:45

问题


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


回答1:


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



回答2:


Minify seems to be one of the easiest ways to shrink Javascript.

Turning on zip at the web server level can also help.




回答3:


Rather than tweaking your files directly, I would recommend compressing them. Most clients support it.

I think you'll find that this is easier and just as effective.

More details from Jeff's adventures with it.




回答4:


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




回答5:


I'm surprised no one suggested gzipping your code. A straight ~50% saving there!




回答6:


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:


Here are the online tools by which you can do this:-

  • For minifying java script codes, you can use Javascript Online Minifier Tool. This is currently best js minifier/un-minifiers

  • For minifying css codes, you can use CSS Minifier/Minify Tool. This is currently best css minifier/un-minifiers

Above are the tools which I seems to be useful for you.




回答8:


Dojo Shrinksafe is a Javascript compressor that uses a real JS interpreter, so it won't break your code. The other ones can work well, but Shrinksafe is a good one to use in a build script, since you shouldn't have to re-test the compressed script.




回答9:


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.




回答10:


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




回答11:


Google hosts a handful of pre-compressed JavaScript library files that you can include in your own site. Not only does Google provide the bandwidth for this, but based on most browser's file caching algorithms, if the user has already downloaded the file from Google for another site they won't have to do it again for yours. A nice little bonus for some of the 90k+ JS libraries out there.




回答12:


For javascript, I use Dean Edwards's Javascript Packer. It's been ported to .NET, perl, php4, php5, WSH, and there's even an aptana plugin.

Javascript packing comes in a few flavours - some just strip out comments and whitespace, others will change your variable names to be concise, and others, well, I don't even know what they do, but the output sure is small. The high-end compression works by using the eval() function, which puts some extra burden on the client, so if your scripts are particularly complicated, or you're designing for slower hardware, keep that in mind. the Javascript packer gives you the option for which compression level you want to use.

For CSS, the best you can do is strip whitespace and comments. Thankfully that means that you can achieve that with a one-line function:

function compressCSS($css) {
    return
        preg_replace(
            array('@\s\s+@','@(\w+:)\s*([\w\s,#]+;?)@'),
            array(' ','$1$2'),
            str_replace(
                array("\r","\n","\t",' {','} ',';}'),
                array('','','','{','}','}'),
                preg_replace('@/\*[^*]*\*+([^/][^*]*\*+)*/@', '', $css)
            )
        )
    ;
}

While that function and the Javascript packer will reduce the file size of individual files, to get the best performance from your site, you'll also want to be reducing the number of HTTP requests you make. Each Javascript and CSS file is a separate request, so combining them into one file each will the the optimal result. Instead of trying to maintain a single bohemoth JS file, you can use the program/technique I've written on my blog (shameless self plug) at http://spadgos.com/?p=32

The program basically reads a "build script"-type file which will simultaneously combine and compress multiple Javascript and CSS files into one (of each) for you (or more, if you want). There are several options for the output and display of all files. There's a larger write-up there, and the source is freely available.




回答13:


YUI Compressor does a pretty good job at compressing both Javascript and CSS.




回答14:


YUI Compressor has my vote, for the simple reason that instead of just performing regular expression transformations on the code, it actually builds a parse tree of the code, similar to a Javascript interpreter, and then compresses it that way. It is usually very careful about how it handles the compression of identifiers.

Additionally it has a CSS compression mode, which I haven't played with as much.




回答15:


CssTidy is the best CSS optimizer of which I am aware. It (configurably) strips comments, eliminates whitespaces, rewrites to use the many shorthand rules nickf mentioned, etc. Compressing the result helps too, as others have mentioned.

The compression ratio can be fairly dramatic, and it frees you to comment your CSS extensively without worrying about the file size.

Unfortunately, this level of preprocessing interacts with some of the popular "css hacks" in unpredictable (or predictable but undesired) ways. Some work, some don't, and some require configuration settings which reduce the level of compression for other things (especially comments).




回答16:


I found JSCompress a nice way to not only minify a JavaScript, but to combine multiple scripts. Useful if you're only using the various scripts once. Saved 70% before compression (and something similar after compression too).

Remember to add back in any copyright notices afterwards.




回答17:


I'd give a test-drive to the new runtime optimizers in ASP.Net published on http://www.codeplex.com/NCOptimizer




回答18:


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.



来源:https://stackoverflow.com/questions/65491/what-is-the-best-method-to-reduce-the-size-of-my-javascript-and-css-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!