如何使用 CSS 和 Javascript 缩小 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11568874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:41:50  来源:igfitidea点击:

How to minify HTML with CSS and Javascript?

javascriptjqueryhtmlcsscompression

提问by ?mega

I have a .html document with CSS and Javascript inside of document (no external files). Is there some online tool that would minifydocument and Javascript to some very small footprint? I saw many scripts kind of unreadable, where all variables and function names are replaced with one-letter names, etc. Please advice.

我有一个包含 CSS 和 Javascript 的 .html 文档(没有外部文件)。是否有一些在线工具可以将文档和 Javascript缩小到非常小的占用空间?我看到很多脚本有点不可读,其中所有变量和函数名称都替换为一个字母的名称等。请指教。

采纳答案by GG.

Edit 2 (Feb 22, 2017):Now the best tool to minify your assets (and a whole lot more, by adding loaders and plugins) is definitely Webpack.

编辑 2(2017 年 2 月 22 日):现在缩小资产(以及更多,通过添加加载器和插件)的最佳工具绝对是Webpack

Example of config to move all your .cssin one file and minify it:

将所有内容移动.css到一个文件中并缩小它的配置示例:

{
  test: /\.css$/,
  use: [
    {
      loader: 'css-loader',
      options: {
        minimize: true
      }
    }
  ]
}


Edit 1 (Sept 16, 2014):Even better, now you have task runnerslike Gulpor Grunt.

编辑 1(2014 年 9 月 16 日):更好的是,现在您拥有GulpGrunt任务运行器

Task runners are small applications that are used to automate many of the time consuming, boring (but very important) tasks that you have to do while developing a project. These include tasks such as running tests, concatenating files, minification, and CSS preprocessing. By simply creating a task file, you can instruct the task runner to automatically take care of just about any development task you can think of as you make changes to your files. It's a very simple idea that will save you a lot of time and allow you to stay focused on development.

任务运行器是小型应用程序,用于自动执行您在开发项目时必须执行的许多耗时、枯燥(但非常重要)的任务。其中包括运行测试、连接文件、缩小和 CSS 预处理等任务。通过简单地创建一个任务文件,您可以指示任务运行器在您对文件进行更改时自动处理您能想到的任何开发任务。这是一个非常简单的想法,可以为您节省大量时间并让您专注于开发。

Must read: Getting started with Gulp.js

必读:Gulp.js 入门

Example of task with JavaScript concatenation and minification (and JSHint):

使用 JavaScript 连接和缩小(和 JSHint)的任务示例:

gulp.task('scripts', function() {
  return gulp.src('src/scripts/**/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(concat('main.js'))
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(notify({ message: 'Scripts task complete' }));
});


Original answer (Jul 19, 2012):I advise the HTML5 Boilerplate Build Scriptwhich can minify your JS and CSS.

原始答案(2012 年 7 月 19 日):我建议使用HTML5 Boilerplate Build Script,它可以缩小您的 JS 和 CSS。

回答by Stano

Good javascript compressor is also Google's Closure Compilerand vice versa, to make compressed code a bit better readible you can use Javascript Beautifier. You can also have a look at phpEasyMinproject.

好的 javascript 压缩器也是Google 的 Closure Compiler,反之亦然,为了使压缩代码的可读性更好一点,您可以使用Javascript Beautifier。您还可以查看phpEasyMin项目。

回答by o.v.

Closure compilerhas been correctly recommended for JS; but not many are aware of Google's Closure stylesheets. One of the closure stylesheets features is renaming, where

已为 JS 正确推荐了Closure 编译器;但没有多少人知道 Google 的Closure stylesheets。闭包样式表的功能之一是重命名,其中

<style>
  .descriptive-parent-class-name .descriptive-element-class-name {color:red;}
</style>
<div class="descriptive-parent-class-name">
  <p class="descriptive-element-class-name">Lorem ipsum</p>
  <p class="descriptive-element-class-name">Lorem ipsum</p>
</div>

would become

会成为

<style>
  .a-b .a-c {color:red;}
</style>
<div class="a-b">
  <p class="a-c">Lorem ipsum</p>
  <p class="a-c">Lorem ipsum</p>
</div>

There'll be further minification too; and given the fact that OP indicates all resources are included into the html, this may end up saving quite a bit in traffic overhead.

也会有进一步的缩小;并且鉴于 OP 指示所有资源都包含在 html 中,这最终可能会节省相当多的流量开销。

NB: if you inspect any Google search results page, you'll see their class and ID names are almost never longer than 4 random characters

注意:如果您检查任何 Google 搜索结果页面,您会看到它们的类和 ID 名称几乎不会超过 4 个随机字符

回答by David Titarenco

By using one of the manyavailableminifiers.

通过使用许多可用的缩小器之一

There are evensomethat minify CSS.

甚至一些是缩小CSS。

回答by Christophe

I am afraid you'll have to do it in two steps:

恐怕您必须分两步完成:

  1. manual search and replace of global objects in a text editor
  2. minifiers to finish the job on css and js
  1. 在文本编辑器中手动搜索和替换全局对象
  2. minifiers 来完成 css 和 js 的工作

I had a similar question some time ago (about global objects and object keys). The answer I got was that no tool will make assumptions about the global context. In your example, they won't minify "pageLoad" because it might be used by another html or js fragment you didn't provide.

前段时间我有一个类似的问题(关于全局对象和对象键)。我得到的答案是,没有任何工具会对全球背景做出假设。在您的示例中,它们不会缩小“pageLoad”,因为它可能被您未提供的另一个 html 或 js 片段使用。

A workaround in your example would be to make the pageLoad function local and add the onload event dynamically in the script:

您的示例中的解决方法是将 pageLoad 函数设为本地并在脚本中动态添加 onload 事件:

elt.onload=function(){pageLoad();};

回答by austincheney

Try http://prettydiff.com/. It offers automatic language detection and can minify html, css, and javascript. This tool presumes that script tags without a mime type or with a javascript relevant mime type must contain either javascript or nothing. Likewise, style tags without a mime type or with the "text/css" mime type are presumed to contain CSS. The CSS and JavaScript are minified accordingly. The tool itself is written in javascript. There is no reason you should have to use more than one tool.

试试http://prettydiff.com/。它提供自动语言检测并可以缩小 html、css 和 javascript。此工具假定没有 mime 类型或具有 javascript 相关 mime 类型的脚本标签必须包含 javascript 或不包含任何内容。同样,没有 mime 类型或具有“text/css” mime 类型的样式标签被假定为包含 CSS。CSS 和 JavaScript 相应地缩小了。该工具本身是用 javascript 编写的。您没有理由必须使用多个工具。

回答by Zeta

While JavaScript code can be compressed and decompressed within JavaScript (see other answers), it's actually hard to achieve the same result in CSS. There is currently no tool that will do more than remove unnecessary whitespace (see also Are there any agressive CSS Minification tools?), since identifier and class names cannot be changed without destroying the link between HTML and CSS.

虽然可以在 JavaScript 中压缩和解压缩 JavaScript 代码(请参阅其他答案),但实际上很难在 CSS 中实现相同的结果。目前没有任何工具可以做的不仅仅是删除不必要的空白(另请参阅是否有任何积极的 CSS 缩小工具?),因为在不破坏 HTML 和 CSS 之间的链接的情况下无法更改标识符和类名。

Also, you can't remove anything from HTML markup except whitespace. Well, you could minify the class names and identifier, but there's currently no tool that will update those minified values in your CSS/JS files, so this would render your website ugly and broken. And even empty elements are often needed in order to get some CSS effects right (yes, I'm looking at you, IE6). This applies to JavaScript function names too.

此外,除了空格之外,您不能从 HTML 标记中删除任何内容。好吧,您可以缩小类名和标识符,但目前没有工具可以更新 CSS/JS 文件中这些缩小的值,因此这会使您的网站变得丑陋和损坏。为了获得正确的 CSS 效果,甚至经常需要空元素(是的,我在看你,IE6)。这也适用于 JavaScript 函数名称。

TL;DR: Unfortunately there's no all-in-one-minify-everything tool. The closest thing is htmlcompressor.

TL;DR:不幸的是,没有一体化的缩小一切工具。最接近的是htmlcompressor

回答by Andrey Taritsyn

I recommend you to try WebMarkupMin Online.

我建议您尝试WebMarkupMin Online

The WebMarkupMin Online a free online tools to minify your HTML, XHTML and XML code. HTML and XHTML minifiers supports the minification of CSS code from styletags and attributes, and minification of JavaScript code from scripttags, event attributes and hyperlinks with javascript:pseudo-protocol. These minifiers supports multiple algorithms of CSS minification (Mads Kristensen's Efficient stylesheet minifier, Microsoft Ajax CSS Minifierand YUI CSS Compressor) and JavaScript minification (Douglas Crockford's JSMin, Microsoft Ajax JS Minifierand YUI JS Compressor).

WebMarkupMin Online 是一个免费的在线工具,用于缩小您的 HTML、XHTML 和 XML 代码。HTML 和 XHTML minifiers 支持从style标签和属性中缩减 CSS 代码,以及从script带有javascript:伪协议的标签、事件属性和超链接中缩减JavaScript 代码。这些压缩器支持多种CSS 压缩算法(Mads Kristensen 的Efficient stylesheet minifierMicrosoft Ajax CSS MinifierYUI CSS Compressor)和 JavaScript压缩(Douglas Crockford 的JSMinMicrosoft Ajax JS MinifierYUI JS Compressor)。

These tools is based on WebMarkupMinlibrary.

这些工具基于WebMarkupMin库。

回答by Rasmus

Have never tried it but have heard real good reviews of Google's Closure compiler..You may want to try it out

从未尝试过,但听说过对 Google Closure 编译器的好评。您可能想尝试一下