简体   繁体   English

减少Javascript和CSS文件大小的最佳方法是什么?

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

使用大型和/或多个Javascript和CSS文件时,减少文件大小的最佳方法是什么?

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 . 您可以随时使用Dean Edward的Javascript Packer等工具,但对于CSS,请花点时间学习CSS速记 Eg 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. 此外,使用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: 例如,如果您知道您的站点将使用一个font-family,请为body标签中的所有元素定义,如下所示:

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. 另一件可以帮助的事情是将CSS和JavaScript作为文件而不是内联或每页的头部。 That way your server only has to serve them once to the browser after that browser will go from cache. 这样,在浏览器从缓存中转出后,您的服务器只需向浏览器提供一次。

Including Javascript 包括Javascript

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

Including CSS 包括CSS

<link rel="stylesheet" href="/css/myStyle.css" type="text/css" media="All" />

Minify seems to be one of the easiest ways to shrink Javascript. Minify似乎是缩小Javascript的最简单方法之一。

Turning on zip at the web server level can also help. 在Web服务器级别打开zip也可以提供帮助。

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 . 来自杰夫的冒险经历的更多细节

I'm surprised no one suggested gzipping your code. 我很惊讶没有人建议你压缩你的代码。 A straight ~50% saving there! 那里直接节省50%!

Compression and minify-ing (removing whitespace) are a start. 压缩和缩小(删除空格)是一个开始。

Additionally: 另外:

  1. Combine all of your JavaScript and CSS includes into a single file. 将所有JavaScript和CSS包含在一个文件中。 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. 使用缓存控制 http标头在Web服务器级别启用缓存 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" />

Here are the online tools by which you can do this:- 以下是可以执行此操作的在线工具: -

  • For HTML, CSS or JS minifier, you can use https://cssminifiers.com . 对于HTML,CSS或JS minifier,您可以使用https://cssminifiers.com This is currently best css minigier/un-minifier 这是目前最好的css minigier / un-minifier
  • For compress your HTML, CSS or JS, you can use http://www.htmlminifier.com/ online tool. 要压缩HTML,CSS或JS,可以使用http://www.htmlminifier.com/在线工具。
  • And also you can use http://javascript-minify.com online tool to minify you JS. 而且你也可以使用http://javascript-minify.com在线工具来缩小你的JS。

Above are the tools which I seems to be useful for you. 以上是我觉得对你有用的工具。

See the question: Best javascript compressor 看到问题: 最好的JavaScript压缩器

Depending on whether or not you are going to gzip your JavaScript files may change your choice of compressor. 根据您是否要使用gzip压缩JavaScript文件,可能会改变您对压缩器的选择。 (Currently Packer isn't the best choice if you are also going to gzip, but see the above question for the current best answer) (如果你也打算使用gzip,目前Packer不是最佳选择,但请参阅上面的问题以获得当前的最佳答案)

Dojo Shrinksafe is a Javascript compressor that uses a real JS interpreter, so it won't break your code. Dojo Shrinksafe是一个使用真正的JS解释器的Javascript压缩器,所以它不会破坏你的代码。 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. 其他的可以很好地工作,但Shrinksafe是一个很好的在构建脚本中使用,因为你不必重新测试压缩脚本。

Shrinksafe may help: http://shrinksafe.dojotoolkit.org/ We're using it and it does a pretty good job. Shrinksafe可能有所帮助: http ://shrinksafe.dojotoolkit.org/我们正在使用它并且它做得非常好。 We execute it from an ant build for when packaging our web app. 我们在打包我们的Web应用程序时从ant构建执行它。

帮助YUI压缩器提供一些很好的建议,告诉你如何调整脚本以实现更好的节省。

Google hosts a handful of pre-compressed JavaScript library files that you can include in your own site. Google托管了一些预压缩的JavaScript库文件 ,您可以将这些文件包含在自己的网站中。 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. Google不仅为此提供了带宽,而且基于大多数浏览器的文件缓存算法,如果用户已经从Google下载了另一个网站的文件,则他们不必为您再次执行此操作。 A nice little bonus for some of the 90k+ JS libraries out there. 对于一些90k + JS库来说,这是一个不错的小奖励。

CssTidy is the best CSS optimizer of which I am aware. CssTidy是我所知道的最好的CSS优化器。 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. 压缩比可以相当大,它可以让您免费评论CSS,而不必担心文件大小。

Unfortunately, this level of preprocessing interacts with some of the popular "css hacks" in unpredictable (or predictable but undesired) ways. 不幸的是,这种级别的预处理以一种不可预测(或可预测但不受欢迎)的方式与一些流行的“css hacks”交互。 Some work , some don't, and some require configuration settings which reduce the level of compression for other things (especially comments). 有些工作 ,有些则没有,有些需要配置设置,这会降低其他事物的压缩级别(尤其是注释)。

I found JSCompress a nice way to not only minify a JavaScript, but to combine multiple scripts. 我发现JSCompress不仅可以简化 JavaScript,还可以组合多个脚本。 Useful if you're only using the various scripts once. 如果您只使用一次各种脚本,则非常有用。 Saved 70% before compression (and something similar after compression too). 在压缩之前保存70%(压缩之后也类似)。

Remember to add back in any copyright notices afterwards. 请务必在之后添加任何版权声明。

For javascript, I use Dean Edwards's Javascript Packer . 对于javascript,我使用Dean Edwards的Javascript Packer It's been ported to .NET, perl, php4, php5, WSH, and there's even an aptana plugin. 它被移植到.NET,perl,php4,php5,WSH,甚至还有一个aptana插件。

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. Javascript打包有几种风格 - 有些只是删除注释和空格,有些会改变你的变量名称简洁,而其他人,好吧,我甚至不知道他们做了什么,但输出肯定很小。 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. 高端压缩通过使用eval()函数来工作,这会给客户端带来额外的负担,因此如果您的脚本特别复杂,或者您正在设计较慢的硬件,请记住这一点。 the Javascript packer gives you the option for which compression level you want to use. Javascript打包器为您提供了要使用的压缩级别的选项。

For CSS, the best you can do is strip whitespace and comments. 对于CSS,您可以做的最好的是删除空白和注释。 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. 虽然该函数和Javascript打包器将减少单个文件的文件大小,但为了从您的站点获得最佳性能,您还需要减少所做的HTTP请求的数量。 Each Javascript and CSS file is a separate request, so combining them into one file each will the the optimal result. 每个Javascript和CSS文件都是一个单独的请求,因此将它们组合成一个文件将是最佳结果。 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 你可以在http://spadgos.com/?p=32上使用我在我的博客上写的程序/技术(无耻的自我插件),而不是试图维护一个庞大的JS文件。

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). 该程序基本上读取一个“构建脚本”类型的文件,它将同时将多个Javascript和CSS文件组合并压缩为一个(每个)(或更多,如果你想)。 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. 那里有一个更大的写作,源可以免费获得。

YUI Compressor在压缩Javascript和CSS方面做得非常好。

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. YUI Compressor有我的投票,原因很简单,它不是只对代码执行正则表达式转换,而是实际构建代码的解析树,类似于Javascript解释器,然后以这种方式压缩它。 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. 此外,它有一个CSS压缩模式,我没有玩过多少。

尝试从Boryi压缩您的标准HTML文件(没有嵌入Javascript代码和CSS代码,但可以链接或导入),Javascript代码(正确结束;)和css代码。

我将对在http://www.codeplex.com/NCOptimizer上发布的ASP.Net中的新运行时优化器进行测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM