How to minify JavaScript inside a view page's script block with minimal effort?
I have some page specific scripts that would like to put on specific view pages. But the ASP.NET MVC4 bundling and minification only works with script files, not script code inside a view page.
UPDATE
I took Sohnee's advice to extract the scripts into files. But I need to use them on specific pages so what I end up doing is:
on layout page, i created an optional section for page specific javascript block:
@RenderSection("js", required: false) </body>
then in the view page, let's say Index.cshtml
, i render the script section like such:
@section js{ @Scripts.Render("~/bundles/js/" + Path.GetFileNameWithoutExtension(this.VirtualPath)) }
as you can see, it assumes the javascript filename (index.js
) is the same as the view page name (index.cshtml
). then in the bundle config, i have:
var jsFiles = Directory.GetFiles(HttpContext.Current.Server.MapPath("Scripts/Pages"), "*.js"); foreach (var jsFile in jsFiles) { var bundleName = Path.GetFileNameWithoutExtension(jsFile); bundles.Add(new ScriptBundle("~/bundles/js/" + bundleName).Include( "~/Scripts/pages/" + Path.GetFileName(jsFile))); }
then, if you are on index
page, the HTML output will be:
<script src="/bundles/js/Index?v=ydlmxiUb9gTRm508o0SaIcc8LJwGpVk-V9iUQwxZGCg1"></script> </body>
and if you are on products
page, the HTML output will be:
<script src="/bundles/js/Products?v=ydlmxiUb9gTRm508o0SaIcc8LJwGpVk-V9iUQwxZGCg1"></script> </body>
Go to minifycode.com and click the CSS minifier tab. Then paste the CSS code into the input box and click the Minify CSS button. After the new minified code is generated, copy the code. Then go back to the css file of your website and replace the code with the new minified version.
How Minification Works. Minification works by analyzing and rewriting the text-based parts of a website to reduce its overall file size. Minification extends to scripts, style sheets, and other components that the web browser uses to render the site. Minification is performed on the web server before a response is sent ...
To regain space and improve your page load speed, you must minify the JavaScript code. The minified version of JavaScript code can reduce the file size by as much as 30–90%. Consequently, JavaScript minification has become a familiar ritual for all developers.
You can minify inline scripts using this HTML helper
using Microsoft.Ajax.Utilities; using System; namespace System.Web.Mvc { public class HtmlHelperExtensions { public static MvcHtmlString JsMinify( this HtmlHelper helper, Func<object, object> markup) { string notMinifiedJs = markup.Invoke(helper.ViewContext)?.ToString() ?? ""; var minifier = new Minifier(); var minifiedJs = minifier.MinifyJavaScript(notMinifiedJs, new CodeSettings { EvalTreatment = EvalTreatment.MakeImmediateSafe, PreserveImportantComments = false }); return new MvcHtmlString(minifiedJs); } } }
And inside your Razor View use it like this
<script type="text/javascript"> @Html.JsMinify(@<text> window.Yk = window.Yk || {}; Yk.__load = []; window.$ = function (f) { Yk.__load.push(f); } </text>) </script>
If you use System.Web.Optimization than all necessary dlls are already referenced otherwise you can install WebGrease NuGet package.
Some additional details available here: http://www.cleansoft.lv/minify-inline-javascript-in-asp-net-mvc-with-webgrease/
EDIT: Replaced DynamicInvoke() with Invoke(). No need for runtime checks here, Invoke is much faster than DynamicInvoke. Added .? to check for possible null.
The way to do this with minimal effort is to extract it into a script file. Then you can use bundling and minification just as you want.
If you want to minify it inline, it will be a much greater effort than simply moving the script off-page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With