From: Juriy Zaytsev Date: Mon, 1 Mar 2010 16:35:30 +0000 (-0500) Subject: Slight optimization to `trimWhitespace`. Fix bug with `removeEmptyElements` cutting... X-Git-Url: https://git.ndcode.org/public/gitweb.cgi?a=commitdiff_plain;h=21aa0ecd6779115e1546faa4e7aba54d495c6359;p=html-minifier.git Slight optimization to `trimWhitespace`. Fix bug with `removeEmptyElements` cutting off tags in some cases. --- diff --git a/src/htmlminifier.js b/src/htmlminifier.js index 2276f80..d1c0f7b 100644 --- a/src/htmlminifier.js +++ b/src/htmlminifier.js @@ -21,7 +21,12 @@ } function trimWhitespace(str) { - return (str.trim ? str.trim() : str.replace(/^\s+/, '').replace(/\s+$/, '')); + return str.replace(/^\s+/, '').replace(/\s+$/, ''); + } + if (String.prototype.trim) { + trimWhitespace = function(str) { + return str.trim(); + }; } function collapseWhitespace(str) { @@ -183,6 +188,7 @@ tag = tag.toLowerCase(); currentTag = tag; + currentChars = ''; buffer.push('<', tag); @@ -195,14 +201,20 @@ }, end: function( tag ) { var isElementEmpty = currentChars === '' && tag === currentTag; - if ((options.removeEmptyElements && isElementEmpty && canRemoveElement(tag)) || - (options.removeOptionalTags && isOptionalTag(tag))) { - // noop + if ((options.removeEmptyElements && isElementEmpty && canRemoveElement(tag))) { + // remove last "element" from buffer, return + buffer.splice(buffer.lastIndexOf('<')); + return; + } + else if (options.removeOptionalTags && isOptionalTag(tag)) { + // noop, leave start tag in buffer } else { + // push end tag to buffer buffer.push(''); results.push.apply(results, buffer); } + // flush buffer buffer.length = 0; currentChars = ''; }, diff --git a/tests/index.html b/tests/index.html index ed95793..9cf97eb 100644 --- a/tests/index.html +++ b/tests/index.html @@ -301,6 +301,7 @@ }); test('removing empty elements', function() { + equals(minify('

x

', { removeEmptyElements: true }), '

x

'); equals(minify('

', { removeEmptyElements: true }), ''); @@ -319,6 +320,21 @@ input = '
helloworld
'; output = '
helloworld
'; equals(minify(input, { removeEmptyElements: true }), output); + + input = '

x

'; + output = '

x

'; + equals(minify(input, { removeEmptyElements: true }), output); + + input = '
x
y
blah
foo
z
'; + output = '
x
y
blah
foo
z
'; + equals(minify(input, { removeEmptyElements: true }), output); + + input = ''; + equals(minify(input, { removeEmptyElements: true }), input); + + input = '

'; + output = ''; + equals(minify(input, { removeEmptyElements: true }), output); }); test('collapsing boolean attributes', function(){