- Notifications
You must be signed in to change notification settings - Fork1.6k
HTML, CSS and JavaScript Minification
This page has moved todocs.servicestack.net
As part of our quest to provide a complete and productive solution for developing highly responsive Web and Single Page Apps, ServiceStack now includes minifiers for compressing HTML, CSS and JavaScript available from the newMinifiers class:
varminifiedJs=Minifiers.JavaScript.Compress(js);varminifiedCss=Minifiers.Css.Compress(css);varminifiedHtml=Minifiers.Html.Compress(html);// Also minify in-line CSS and JavaScriptvaradvancedMinifiedHtml=Minifiers.HtmlAdvanced.Compress(html);
Each minifier implements the lightweightICompressor interface making it trivial to mock or subtitute with a custom implementation.
For the JavaScript minifier we're usingExt.Net's C# port of Douglas Crockford's venerableJSMin.
The CSS Minifer uses Mads Kristensen simpleCSS Minifer.
For compressing HTML we're using aC# Port of Google's excellentHTML Compressor which we've further modified to remove the public API's ugly Java-esque idioms and replaced them with C# properties.
TheHtmlCompressor also includes a number of well-documented options which can be customized by configuring the available properties on its concrete type, e.g:
varhtmlCompressor=(HtmlCompressor)Minifier.Html;htmlCompressor.RemoveComments=false;
If your project is not based off one of our optimized Gulp/Grunt.js poweredReact JS and AngularJS Single Page App templates or configured to use our earilernode.js-powered Bundler Web Optimization solution, these built-in minifiers now offers the easiest solution to effortlessly optimize your existing website which is able to work transparently with your existing Razor Views and static.js,.css and.html files without requiring adding any additional external tooling or build steps to your existing development workflow.
Minification of Razor Views is easily enabled by specifyingMinifyHtml=true when registering theRazorFormat plugin:
Plugins.Add(newRazorFormat{MinifyHtml=true,UseAdvancedCompression=true,});
Use theUseAdvancedCompression=true option if you also want to minify inline js/css, although as this requires a bit more processing you'll want to benchmark it to see if it's providing an overall performance benefit to end users. It's a recommended option if you're caching Razor Pages. Another solution is to minimize the use of in-line js/css and move them to static files to avoid needing in-line js/css compression.
With nothing other than the new minifiers, we can leverage the flexibility in ServiceStack'sVirtual File System to provide an elegant solution for minifying static.html,.css and.js resources by simply pre-loading a new InMemory Virtual FileSystem with minified versions of existing files and giving the Memory FS a higher precedence so any matching requests serve up the minified version first. We only need to pre-load the minified versions once on StartUp by overridingGetVirtualFileSources() in the AppHost:
publicoverrideList<IVirtualPathProvider>GetVirtualFileSources(){varexistingProviders=base.GetVirtualFileSources();varmemFs=newInMemoryVirtualPathProvider(this);//Get existing Local FileSystem Providervarfs=existingProviders.First(x=>xisFileSystemVirtualPathProvider);//Process all .html files:foreach(varfileinfs.GetAllMatchingFiles("*.html")){varcontents=Minifiers.HtmlAdvanced.Compress(file.ReadAllText());memFs.AddFile(file.VirtualPath,contents);}//Process all .css files:foreach(varfileinfs.GetAllMatchingFiles("*.css").Where(file=>!file.VirtualPath.EndsWith(".min.css")))//ignore pre-minified .css{varcontents=Minifiers.Css.Compress(file.ReadAllText());memFs.AddFile(file.VirtualPath,contents);}//Process all .js filesforeach(varfileinfs.GetAllMatchingFiles("*.js").Where(file=>!file.VirtualPath.EndsWith(".min.js")))//ignore pre-minified .js{try{varjs=file.ReadAllText();varcontents=Minifiers.JavaScript.Compress(js);memFs.AddFile(file.VirtualPath,contents);}catch(Exceptionex){//As JSMin is a strict subset of JavaScript, this can fail on valid JS.//We can report exceptions in StartUpErrors so they're visible in ?debug=requestinfobase.OnStartupException(newException("JSMin Error {0}: {1}".Fmt(file.VirtualPath,ex.Message)));}}//Give new Memory FS the highest priorityexistingProviders.Insert(0,memFs);returnexistingProviders;}
A nice benefit of this approach is that it doesn't pollute your project with minified build artifacts, has excellent runtime performance with the minfied contents being served from Memory and as the file names remain the same, the links in HTML don't need to be rewritten to reference the minified versions. i.e. When a request is made it just looks through the registered virtual path providers and returns the first match, which given the Memory FS was inserted at the start of the list, returns the minified version.
Enabled inservicestack.net
As this was an quick and non-invasive feature to add, we've enabled it on allservicestack.net Razor views and static files. You canview-source:https://servicestack.net/ (as url in Chrome, Firefox or Opera) to see an example of the resulting minified output.
- Why ServiceStack?
- Important role of DTOs
- What is a message based web service?
- Advantages of message based web services
- Why remote services should use separate DTOs
Getting Started
Designing APIs
Reference
Clients
Formats
View Engines4.Razor & Markdown Razor
Hosts
Security
Advanced
- Configuration options
- Access HTTP specific features in services
- Logging
- Serialization/deserialization
- Request/response filters
- Filter attributes
- Concurrency Model
- Built-in profiling
- Form Hijacking Prevention
- Auto-Mapping
- HTTP Utils
- Dump Utils
- Virtual File System
- Config API
- Physical Project Structure
- Modularizing Services
- MVC Integration
- ServiceStack Integration
- Embedded Native Desktop Apps
- Auto Batched Requests
- Versioning
- Multitenancy
Caching
Auto Query
AutoQuery Data1.AutoQuery Memory2.AutoQuery Service3.AutoQuery DynamoDB
Server Events
Service Gateway
Encrypted Messaging
Plugins
Tests
ServiceStackVS
Other Languages
Amazon Web Services
Deployment
Install 3rd Party Products
Use Cases
Performance
Other Products
Future