Class: Squoosh::Squoosher

Inherits:
Object
  • Object
show all
Defined in:
lib/squoosh.rb

Overview

Minify HTML, JavaScript, and CSS using a single set of options. Minified versions of the JavaScript and CSS encountered are cached to speed up minification when the same scripts or inline style sheets appear multiple times.

Constant Summary collapse

DEFAULT_OPTIONS =

Default options for minifying.

  • ++remove_comments++ Remove all comments that aren't "loud"
  • ++omit_tags++ Omit unnecessary start and end tags
  • ++loud_comments++ Keep all comments matching this regex
  • ++minify_javascript++ Minify JavaScript

    Create a new instance of ++Squoosher++.

    Parameters:

    • (defaults to: {})

      options to override the default options

    
    
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    # File 'lib/squoosh.rb', line 68
    
    def initialize(options = {})
      options.each_key do |key|
        unless DEFAULT_OPTIONS.include?(key)
          raise ArgumentError, "Invalid option `#{key}'"
        end
      end
      @options = DEFAULT_OPTIONS.merge(options)
      @js_cache = {}
      @inline_script_cache = {}
      @css_cache = {}
    end

Instance Method Details

#minify_css(content) ⇒ String

Minify CSS using Sassc.

Parameters:

  • the CSS to minify

Returns:

  • the minified CSS



102
103
104
105
106
107
# File 'lib/squoosh.rb', line 102

def minify_css(content)
  @css_cache[content] ||= begin
    root = SassC::Engine.new(content, @options[:sass_options])
    root.render.rstrip
  end
end

#minify_html(content) ⇒ String

Minify HTML and inline JavaScript and CSS.

If the ++content++ does not start with an HTML document type , then ++content++ is returned unchanged.

Parameters:

  • the HTML to minify

Returns:

  • the minified HTML



87
88
89
90
91
92
93
94
95
96
# File 'lib/squoosh.rb', line 87

def minify_html(content)
  doc = Nokogiri.HTML5(content)
  return content unless doc.internal_subset&.html5_dtd?

  remove_comments(doc) if @options[:remove_comments]
  compress_javascript(doc) if @options[:minify_javascript]
  compress_css(doc) if @options[:minify_css]
  doc.children.each { |c| compress_spaces(c) } if @options[:compress_spaces]
  doc.children.map { |node| stringify_node(node) }.join
end

#minify_js(content) ⇒ String

Minify JavaScript using Uglify.

Parameters:

  • the JavaScript to minify

Returns:

  • the minified JavaScript



113
114
115
# File 'lib/squoosh.rb', line 113

def minify_js(content)
  @js_cache[content] ||= uglify(content, @options[:uglifier_options])
end