We have a handful of ASP.net pages that include more than 50+ lines of javascript specific to that page. We'd like to minify that javascript during our CruiseControl build process.
We already use the YUI Compressor to compress our full javascript and css files. But we can't figure out how to do the Inline javascript.
Is there an MSBuild task to spin through asp.net pages and minify the javascript?
There is an interesting blog and NuGet package called undleMinifyInlineJsCss to handle this
http://weblogs.asp.net/imranbaloch/archive/2012/07/25/bundling-and-minifying-inline-css-and-js.aspx
I would extract javascript into methods and move them into .js files. and call the functions instead with the relevant parameters from the pages. Not a complicated procedure and much easier to maintain (less code). You can also benefit from client side content caching.
Also: Not sure if it helps but Google's Closure looks really good.
http://code.google.com/closure/
Compression options: http://code.google.com/closure/compiler/docs/api-tutorial3.html
Available as Java executable or web service.
You won't be able to do this without custom coding. Easiest way would probably to create a PreBuild step in the msbuild file which spits through all the .aspx files and regexes all the javascript out. Then use YUI to minify the content and replace the original by the minified version.
You might also want to check MbCompression which compresses alot including your asp.net pages, although I don't believe it also minifies the inline javascript.
It is possible to bundle and minify inline javascript. With templated Razor helpers you could create an extension method like the one below:
public static MvcHtmlString AddScriptSource(this HtmlHelper helper, Func<dynamic, HelperResult> source, string key)
{
string scriptSource = source(null).ToHtmlString();
// Cache scriptSource here
return MvcHtmlString.Empty;
}
Which you would use like this:
#Html.AddScriptSource(#<text>$(document).ready(function() { $('h1').text('The current controller is #ViewContext.RouteData.Values["controller"].ToString()'); });</text>, "test")
I created a bundler and minifier around this a few weeks ago at:
https://github.com/philpeace/CodePeace.StrawberryJam
ASP.NET now has bundling and minification built in as of MVC 4 (it is also available for web forms and web pages as well)
http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
Related
I want to minify Razor views (.cshtml files) on compile-time.
Currently, I use WebMarkupMin, but it minifies the HTML on runtime,
So, how can I minify .cshtml files on compile-time?
I built a very trivial and easy to set up and easy to understand minifier for Razor and ASP.NET MVC 5. It just replaces multiple spaces with one, but that often has the biggest impact while having the least amount of side-effects.
Have a look if you're interested: https://github.com/tompazourek/RazorHtmlMinifier.Mvc5
Usually, it's recommended to use gzip encoding to minify HTTP responses, but I found out that if you minify the HTML before gzipping, you can still get around 11% smaller responses on average. In my opinion, it's still worth it.
You can choose to minify your files at anytime (build-time) using the method outlined in this post: https://debugandrelease.blogspot.com/2018/11/automatically-minifying-cshtml-files-in.html
It makes use of a task runner to create minified .cshtml files. In development, you will work with the unminified versions of the files, but in higher environments, the minified .cshtml files will automatically be used. Please see the post for more details on how to set it up, or view the sample github sample repository linked at the end of the post.
I'm right now using asp.net mvc 4.5 in my projects . I like the way asp.net MVC is designed and works, but i am struggling with the script and styles sheet management.
Every page of my project use different style sheet and scripts files so i can not add all the scripts and style sheet file in the layout file as it is not the good technique & increase page loading time , i want to add those related files on each page where they are needed. suggest me a good solution
You could register a section in your layout:
#RenderSection("scripts", required: false)
and then in each view override this section and define any custom scripts related to it:
#section scripts {
<script type="text/javascript" src="#Url.Content("~/scripts/myscript.js")"></script>
}
Using this same technique you could define another section for the custom stylesheets.
This being said, if you take advantage of the built-in bundling and minification mechanism, it might be more effective to have a single minified and compressed file rather than multiple files because the browser will need to make separate HTTP request to retrieve them.
i would recommend using ClientDipendancy Framework.
https://github.com/Shazwazza/ClientDependency
I have this:
bundles.Add(new StyleBundle("~/Content/Styles/Default").Include("~/Content/Styles/Default/Site.css"));
On my sites i have this:
#section Styles
{
#Styles.Render("~/Content/Styles/Default"))
}
My _Layout.cshtml looks like this:
#RenderSection("Styles", true)
Everything looks good, eh? Well, not really. When i compiled my application in release mode, decided to publish it, this is what it renders:
<link href="/Content/Styles/Default?v=78dkNySP_xsiuzsgxCx_GGnnHzYS-B8nNdnXqcl47XI1" rel="stylesheet">
Instead of generating href to a file, it generates some kind of id? Guid? Why? O.o
This is how bundles work. It's main purpose is for you to combine multiple CSS (and JS files for that matter) files into one package. e.g. you no longer have to put all your css (and js) into one huge file. Just split it up into sections, then add it into your bundles, and it packages it up into one item. Less web requests, the faster your page load time.
e.g. Lets say you had 2 css files. One's the main, but you had one for your menu system.
bundles.Add(new StyleBundle("~/Content/Styles/Default").Include(
"~/Content/Styles/Default/Site.css",
"~/Content/Styles/Default/Menu.css"));
This would show up as a single call with the GUID type code (to prevent caching on file changes) on the URL. This URL will link to a minified and bundled css.
But my browser cannot read that! There is no physical path to a file!
It's a sort of virtual file. MVC's bundling uses the routing engine to point it to a combined and minified version of a particle bundle.
I'm using jQuery plugins in an ASP.Net MVC site.
I've often to include CSS and JS files as required by the plugins I use in every page. So I want to centralize all those dependencies in a single place in my app. thus if a dependency for a given plug-in is changed or updated, I'll only have to modify a single place in my app.
I've thought in two possible solutions:
Extend the HTMLHelper with a partial method
like GetPlugin("jqgrid"); that
will print out all the script and
style tags needed.
Create a partial view for each
pluginlike jqGridDependencies.ascx
that will contain the script and
style tags needed.
Do you have any other idea? what do you think of both proposals?
Could http://combres.codeplex.com/ provide you with a framework for this.
My only personal objection to this method is that each individual pages will have a unique JavaScript/CSS file where as if you combined and compressed everything into one and simply used classes and events to trigger the JavaScript enhancements as and when needed your site would run a lot faster.
I prefer the use of external css and javascript files. There are however many cases where the content of a javascript or css file needs to be dynamic. I'll usually just transfer the javascript or css to inline or inpage code in my aspx page and handle the dynamic stuff there.
Does anyone have a better approach? Would there be a way to generate entire js or css files using asp.net's regular templating language?
I'm currently using webforms but I'd be interested in solving this issue in MVC as well.
Thanks
I've used a HTTPHandler to send back dynamic javascript before. But not something that inherits from System.Web.UI.Page.
Using a HTTPHandler and an ASHX or AXD is the "ASP.Net" way to send back resources dynamically.
I have used handlers for dynamic css. Depending on what you need, you can do the same for js files.
I had a css file with placeholders for the pieces that needed to be dynamic like ##bacgroundcolor##, and the handler just replaced as appropriate.
I have also used an approach where I use css classes to mark html elements that need special behaviors. Then the static js, looks for this elements and hook the appropriate handlers. This is something that certainly would be even easier with jquery (I did it with regular js back then :().
I've done this in an aspx page before, but in my opinion the WebForm style doesn't suit itself well to rendering strictly javascript or CSS. Every time I've done it, the page has ended up looking quite a bit like classic ASP.
hopefully the actual JavaScript you are using would stay static and you would just pass parameters to the JavaScript methods.
I have taken JavaScript code that had been in the markup of a page and containing things like <%= control.ClientID %> and replaced it with static JavaScript. I refactored the code into a class, I then refactored these variable parts into class members. The page creates an instance of the class, with things like ClientID set. The functions can then be static.