Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minify JavaScript inside script block on view pages

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> 
like image 478
Ray Cheng Avatar asked Nov 01 '12 16:11

Ray Cheng


People also ask

How do I minify JavaScript code?

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 does JavaScript Minifier work?

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 ...

Should JavaScript be Minified?

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.


2 Answers

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.

like image 134
samfromlv Avatar answered Oct 05 '22 23:10

samfromlv


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.

like image 36
Fenton Avatar answered Oct 05 '22 22:10

Fenton