Introduction

To use the API simply perform a POST request to https://htmlcompressor.com/compress with at least the code parameter containing the code you want to compress / minify. In the following integration examples we make use of curl in a linux terminal for its simplicity, brevity and power.

Compressing a code snippet

curl -X POST -s --data-urlencode "code=<script> alert( 1 ); </script>" https://htmlcompressor.com/compress

To compress an html code snippet simply POST the code to the API url.

Compressing a file and overwriting only if successful

curl -X POST -s --fail --compressed --data-urlencode "code@index.html" --output "index.html" https://htmlcompressor.com/compress

By default the HTMLCompressor API asumes that the received code is html and performs a safe html minimization including any contained CSS and JavaScript code. The default output_mode is text. When the compression generates any errors the API returns an http status 400 Bad Request, therefore in the previous example the --fail parameter is used to prevent curl from outputting anything on http errors.

Recursively compressing all PHP, HTML, CSS and JS files inside a directory

while IFS= read -d $'\0' -r file; do curl -X POST -s --fail --compressed --data "code_type=${file##*.}" --data-urlencode "code@$file" --output "$file" https://htmlcompressor.com/compress && echo "$file: (OK)" || echo "$file: (ERROR)"; done < <(find /path/to/directory -type f -regextype egrep -regex '.*\.(php|html|css|js)' -print0)

This one-liner example recursively processes all the files with extensions .php., .html, .css and .js in the specified directory while providing the corresponding code_type parameter to the API and showing the progress and success of each file.

An alias for your shell

alias htmlc='htmlc(){ [ ! -z "$1" ] &&  while IFS= read -d $'\''\0'\'' -r file; do curl -X POST -s --fail --compressed --data "code_type=${file##*.}" --data-urlencode "code@$file" --output "$file" https://htmlcompressor.com/compress && echo "$file: (OK)" || echo "$file: (ERROR)"; done < <(find "$1" -type f -regextype egrep -regex ".*\.(php|html|css|js)" -print0); unset -f htmlc; }; htmlc'

To make better use of the previous example in a comfortable manner add this alias to your shell. To compress a php file in your local computer simply do $ htmlc index.php or to process a directory recursively do $ htmlc projects/web.

Integration with a code editor

#!/bin/bash
STDIN=$(cat <&0); echo -n "$STDIN" | curl -X POST -s --fail --compressed --data "code_type=${1:-html}" --data "js_engine=${2:-yui}" --data-urlencode "code@-" https://htmlcompressor.com/compress || echo -n "$STDIN"

This small script reads the code to compress from STDIN and allows 2 optional parameters: code_type and js_engine. If the compression is successful it returns the compressed code, otherwise the original code. For this example we are going to use Geany code editor. Save this script as htmlcompressor-stdin.sh then in Geany go to Edit / Format / Send Selection to / Set Custom Commands, click Add and insert the command as htmlcompressor-stdin.sh js closure and add some identifying label. Use htmlcompressor-stdin.sh css for CSS and htmlcompressor-stdin.sh for HTML. Now you can select any text in your editor and have it compressed with HTMLCompressor API without leaving your code editor. Awesome!

Integration with the linux desktop

#!/bin/bash

# Open a new terminal if processing a folder and running on a dumb terminal
if [[ "$TERM" == "dumb" ]] && [[ -d "$1" ]]; then
    xterm -geometry 120x40-100+100 -fa 'Monospace' -fs 10 -e "$0" "$1" "--wait"
    exit
fi

# Compress PHP, HTML, CSS and JS files in current dir or given as argument (file or dir arg)
while IFS= read -d $'\0' -r file; do
    curl -X POST -s --fail --compressed --data "code_type=${file##*.}" --data-urlencode "code@$file" --output "$file" https://htmlcompressor.com/compress && echo "$file: (OK)" || echo "$file: (ERROR)"
done < <(find "${1:-.}" -regextype egrep -regex '.*\.(php|html|css|js)' -print0)

# Wait for keypress to close xterm
[[ "$2" == "--wait" ]] && read -p "Press enter key to close..."

This basic script shows how easy it is to use the API to integrate in a linux desktop workflow. Save it as htmlcompressor.sh and use it as a custom command to execute for directories and the file types you want to process. The script will process single files silently and will open a terminal with progress and status for directories. Extend and modify as you see fit.

Integration with the Windows desktop

@echo off
setlocal EnableExtensions EnableDelayedExpansion

set CURL="c:\curl\curl.exe"
set SELF=%~n0
set ARG=%~1

if "%ARG%" == "" goto help
if not exist "%ARG%" goto not_found

pushd "%ARG%" >nul 2>&1 && (
    for /R %%f in (*.php, *.html, *.css, *.js) do call :PROCESS_FILE "%%f"
    popd
    echo Press any key to continue...
    pause >nul
) || (
    call :PROCESS_FILE "%ARG%"
    timeout /t 3
)

goto end

:PROCESS_FILE
    set FILE_NAME=%~1
    for /f "delims=" %%a in ("%FILE_NAME%") do set BASE_NAME=%%~na
    for /f "delims=" %%a in ("%FILE_NAME%") do set EXT=%%~xa
    for /f "delims=" %%a in ("%BASE_NAME%") do set EXTSUB=%%~xa

    if "%EXT%" == ".html" (
        call :API_POST html "%FILE_NAME%"
    ) else if "%EXT%" == ".php" (
        call :API_POST php "%FILE_NAME%"
    ) else if "%EXT%" == ".css" (
        if NOT "%EXTSUB%" == ".min" call :API_POST css "%FILE_NAME%"
    ) else if "%EXT%" == ".js" (
        if NOT "%EXTSUB%" == ".min" call :API_POST js "%FILE_NAME%"
    )
exit /B 0

:API_POST
    set CODE_TYPE=%1
    set FILE=%~2
    %CURL% -X POST -s --fail --compressed --data "code_type=%CODE_TYPE%" --data-urlencode "code@%FILE%" --output "%FILE%" https://htmlcompressor.com/compress && echo %FILE%: (OK) || echo %FILE%: (ERROR)
exit /B 0

:help
echo Please use %SELF% file.^(css^|html^|js^|php^) or %SELF% dir.
goto end

:not_found
echo The given parameter is not an existing file or directory!

:end

This batch script makes it very easy to use the API on a Windows desktop. Download curl for windows and extract the contents of the bin folder to C:\curl or edit the CURL path in the script. Save it as htmlc.bat and then copy it to %APPDATA%\Microsoft\Windows\SendTo so it shows up in your Send to folder. You can also create a shortcut on your desktop to drag files to compress or use it as a commandline tool. Extend and modify as you see fit.

 

HTMLCompressor API reference

NOTICE: Usage of the API is limited to 30 requests per minute in order to preserve the public service availability. HTMLCompressor runs on a modest server and this limit may change during the beta period to prevent the server from overloading.

Overview

To request compressed code from the HTMLCompressor public API, you must send an HTTP POST request to the URL https://htmlcompressor.com/compress with at least the code parameter containing the code you want to compress.

Boolean parameters are enabled with 1 and disabled with 0. If the parameter is not specified, the default value is used.

The default parameters are the equivalent to:

  • code_type=html
  • output_format=text
  • html_level=1
  • minimize_style=1
  • minimize_events=1
  • minimize_js_href=1
  • minimize_css=1
  • minimize_js=1
  • js_engine=yui

Required Parameters

code

Source code to compress.

General Parameters

code_type (default html)

The type of code to process.

html

HTML code.

php

HTML code mixed with PHP code.

asp

HTML code mixed with ASP code.

smarty

HTML code mixed with SMARTY code.

js

JavaScript code.

js_php

Javascript code mixed with PHP code.

js_asp

Javascript code mixed with ASP code.

js_smarty

Javascript code mixed with SMARTY code.

css

CSS code.

css_php

CSS code mixed with PHP code.

css_asp

CSS code mixed with ASP code.

css_smarty

CSS code mixed with SMARTY code.

blogger

Blogger template code.

output_format (default text)

The output format for HTMLCompressor API replies.

text

Text format returns the compressed code. On error an http status 400 Bad Request response code is returned along with the error messages.

json

When using json output format the API returns a JSON object. In this mode JavaScript compression errors do not trigger 400 Bad Request response code since the errors are included in the error property of the returned object.

The possible JSON object keys are:
  • success (boolean)
  • result (string),
  • error (array with details about compression errors)
  • output (array of verbose messages)
  • empty_blocks (array of warnings about empty blocks)
  • log (array with any system log messages)
A successful response looks like this:
{
    "success": true,
    "result": "<script>alert(1);<\/script>"
}
A response with compression errors looks like this:
{
    "success": false,
    "result": "<script>alert( 1 ;<\/script>",
    "error": {
        "script": ["[ERROR] in temp.js\n  1:10:missing ) after argument list\n[ERROR] in temp.js\n  1:0:Compilation produced 1 syntax errors.\n"]
    }
}

verbose (default 0)

Enable general notices and warnings.

HTML Parameters

html_level (default 1)

HTML compression level.

0

Do not minimize.

1

Safe minimization.

2

Advanced minimization.

3

Aggressive minimization.

html_single_line (default 0)

Replaces new line characters from output with one space.

html_keep_quotes (default 0)

Prevents removing quotes from attribute values in document types that support this feature.

html_strip_quotes (default 0)

Strip quotes regardless of DOCTYPE.

minimize_style (default 1)

Minimize CSS inside style attributes.

minimize_events (default 1)

Minimize JavaScript events in html tags.

minimize_js_href (default 1)

Minimize JavaScript in href.

keep_comments (default 0)

Preserve all x/html comments.

keep_ssi (default 0)

Preserve SSI directives.

keep_char

HTML comments that include the specified character will not be removed. For example: @ will keep <!--@ copyright notice --> comment intact.

minimize_css (default 1)

Minimize CSS code inside HTML.

minimize_js (default 1)

Minimize JavaScript code inside HTML.

minimize_js_ph (default 0)

Minimize JavaScript code containing server side code (ASP, PHP, SMARTY).

html_optional_cdata (default 0)

If the compressor engine cannot determine the document type and the inline JavaScript or CSS code contains < or & characters, we enclose the code between /*<![CDATA[*/ and /*]]>*/ tags. Having this option checked tells the compressor engine that the document is not xml (and this includes xhtml), so CDATA enclosing is not necessary.

CSS Minimization Parameters

css_lb_num (default 0)

Add a newline character after the specified column number.

JavaScript Minimization Parameters

js_engine (default yui)

Which JavaScript compression engine to use.

jsmin

Use Douglas Crockford JSMin.

yui

Use Yahoo YUI Compressor.

closure

Use Google Closure Compiler.

js_ph_engine (default yui)

Which JavaScript compression engine to use for JavaScript mixed with Server Side Code (ASP, PHP, SMARTY).

jsmin

Use Douglas Crockford JSMin.

yui

Use Yahoo YUI Compressor.

js_fallback (default 0)

If the specified js_engine fails to minimize your code use jsmin and retry minimization.

js_ph_fallback (default 0)

If the specified js_ph_engine fails to minimize your code use jsmin and retry minimization.

Yahoo YUI Compressor Parameters

js_yui_nomunge (default 0)

Do not minimize local symbols (nomunge).

js_yui_preserve (default 0)

Preserve all semicolons.

js_yui_noopt (default 0)

Disable all micro optimizations.

js_yui_lb_num (default 0)

Add a newline character after the specified column number.

js_yui_verbose (default 0)

Verbose output.

Google Closure Compiler Parameters

js_closure_level (default simple)

Closure Compiler compilation level.

spaces

Removes comments and unneeded whitespace characters from the JavaScript code.

simple

Removes comments and unneeded whitespace characters from the JavaScript code. Also renames local symbols and function parameters to shorter versions (munging), and performs various optimizations within expressions and functions.

advanced

Performs all the optimizations used in Simple optimizations level, but also goes way further with extreme compression techniques that transform your code in the local and global scope, renaming not only variables, but also function names and object properties. It also removes unused code and replaces some function calls with the body of the function (inlining) where possible.

js_closure_single_line (default 0)

By default Closure Compiler adds a line break near column number 500. Check this option if you want the compressed javascript to be a single line output.

js_closure_formatting (default 0)

Outputs code in a properly formatted way, which makes it more readable. This is useful to study how the Closure Compiler works, and how does it modify your code. Use it with any of the compression levels.

js_closure_verbose (default 0)

Displays notices and warnings about your code that can help improve it. Recommended only for debugging purposes.

Yahoo YUI Compressor for S.S.C. Parameters

js_ph_yui_nomunge (default 0)

Do not minimize local symbols (nomunge).

js_ph_yui_preserve (default 0)

Preserve all semicolons.

js_ph_yui_noopt (default 0)

Disable all micro optimizations.

js_ph_yui_lb_num (default 0)

Add a newline character after the specified column number.

js_ph_yui_verbose (default 0)

Verbose output.

JavaScript Minimization (S.S.C.) Parameters

js_fallback (default 0)

If the js_engine fails to minimize your code use jsmin and retry minimization.

PHP Minimization Parameters

php_minimize (default 0)

Minimize PHP code.

php_convert_tag (default 0)

Convert PHP short tags.

Smarty Minimization Parameters

smarty_auto_literals (default 0)

Ignores smarty open / close delimiters if they are surrounded by a whitespace character.

smarty_keep_comments (default 0)

Preserve all smarty comments.

 

For a more detailed explanation of each option please visit the HTMLCompressor UI page and check the inline help for each available option.