Minify JavaScript
JavaScriptStrips comments and whitespace from JavaScript.
Filter
rewrite_javascript
· Filter docs
A module filter.
Both frames render identically — that's the goal. The win is in the bytes and requests
below, not the look. They're served live by the mod_pagespeed module on
demo-httpd-1.1.modpagespeed.com; the optimized frame
applies only this filter. Right after a cache purge it may briefly match the original while
the worker rewrites it — reload to see the result.
Measured impact
Total bytes
HTML size
What changed in the source
The page's HTML, before and after this filter. Red lines are removed, green lines are added.
… 5 unchanged lines …
<p>
Expected: Internal 0 External 1 External 2<br/>
Actual:
- <script type="text/javascript" id="int1">
- // This comment will be removed
- var state = 0;
- document.write("Internal " + state);
- state = 1
- </script>
- <script src="rewrite_javascript.js" type="text/javascript" id="ext1">
- </script>
- <script src="rewrite_javascript.js" id="ext2">
+ <script type="text/javascript" id="int1">var state=0;document.write("Internal "+state);state=1</script>
+ <script src="rewrite_javascript.js.pagespeed.jm.1o978_K0_L.js" type="text/javascript" id="ext1"></script>
+ <script src="rewrite_javascript.js.pagespeed.jm.1o978_K0_L.js" id="ext2">
/* Note that the contents and comments of a script block are preserved
if a src is specified. Since they are not executed, it is assumed the
code will be using the script block contents as data. */
… 1 unchanged line …
</script>
</p><p>
External script url:
- <script type="text/javascript">
- /* This comment will also be removed */
- document.write(document.getElementById("ext1").src);
- </script>
+ <script type="text/javascript">document.write(document.getElementById("ext1").src);</script>
</p><p>
Comment in internal script:
- <script type="text/javascript">
- // This comment will be removed too.
- var source = document.getElementById("int1").innerHTML;
- document.write(source.match("comment") ? "yes" : "no");
- </script>
+ <script type="text/javascript">var source=document.getElementById("int1").innerHTML;document.write(source.match("comment")?"yes":"no");</script>
</p><p>
Comment in external script:
- <script type="text/javascript">
- /* Of course, this comment will be removed as well. */
- var source = document.getElementById("ext2").innerHTML;
- document.write(source.match("comment") ? "yes" : "no");
- </script>
+ <script type="text/javascript">var source=document.getElementById("ext2").innerHTML;document.write(source.match("comment")?"yes":"no");</script>
</p>
</body>
</html>
Run this on your own site
This is one of 49 filters the mod_pagespeed module applies in place — self-hosted on Apache, nginx, and IIS. Install and run it: it optimizes right away and adds an the optimized response headers shown above. Open source under the Apache License 2.0 — free in development and in production.