Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to minify JavaScript inside script block on view pages
    primarykey
    data
    text
    <p>How to minify JavaScript inside a view page's script block with minimal effort?</p> <p>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.</p> <p><strong>UPDATE</strong></p> <p>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:</p> <p>on layout page, i created an optional section for page specific javascript block:</p> <pre><code> @RenderSection("js", required: false) &lt;/body&gt; </code></pre> <p>then in the view page, let's say <code>Index.cshtml</code>, i render the script section like such:</p> <pre><code>@section js{ @Scripts.Render("~/bundles/js/" + Path.GetFileNameWithoutExtension(this.VirtualPath)) } </code></pre> <p>as you can see, it assumes the javascript filename (<code>index.js</code>) is the same as the view page name (<code>index.cshtml</code>). then in the bundle config, i have:</p> <pre><code>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))); } </code></pre> <p>then, if you are on <code>index</code> page, the HTML output will be:</p> <pre><code> &lt;script src="/bundles/js/Index?v=ydlmxiUb9gTRm508o0SaIcc8LJwGpVk-V9iUQwxZGCg1"&gt;&lt;/script&gt; &lt;/body&gt; </code></pre> <p>and if you are on <code>products</code> page, the HTML output will be:</p> <pre><code> &lt;script src="/bundles/js/Products?v=ydlmxiUb9gTRm508o0SaIcc8LJwGpVk-V9iUQwxZGCg1"&gt;&lt;/script&gt; &lt;/body&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload