Prevent loading ASP.NET MVC packages more than once

Is there a built-in tracking method if the package is already downloaded? I have several types of editing that require, for example, jquery and jquery.Validate, etc. Libraries. Which I do not need to link to the main page of the layout. Since the page may consist of several different conditional libraries ... ideally, I would like @ scripts.Render to know that I was already referencing the library and not reloading it.

Cheers Tim

+6
source share
4 answers

I think Hao Kung and user108 have pieces of your answer.

Hao Kung refers to the ability of the system to know that you have already included the package on the page and have not added a duplicate. This is similar to what the insert in WordPress script / style does. MVC does not have this yet. You would have to build it yourself.

user108 represents a possible solution to your problem. He says that in your layout you can create an optional "Scripts" section. Then, in views that require jquery validation code, you can include it in the Scripts section of the layout. This will do most of what you are looking for. The only place this doesn't work is that you have multiple view scores on the same page for which all jquery validation code is required.

You can implement this solution quite easily. Here's a SO post to help you get started .

+5
source

It sounds like you're asking for something more like asset management, where you can potentially write scripts more than once and have an API to automatically deduplicate and display the corresponding list. This is on our task list, but so far it is not part of the API.

If this is what you would like, you can vote for it on our codeplex website: This problem

+4
source

Try the following:

public static MvcHtmlString RequireClientScript(this HtmlHelper helper, string scriptPath) { var scripts = helper.ViewContext.HttpContext.Items["client-script-list"] as Dictionary<string, string> ?? new Dictionary<string, string>(); if (!scripts.ContainsKey(scriptPath)) { var sb = new StringBuilder(); var scriptTag = new TagBuilder("script"); scriptTag.Attributes.Add("type", "text/javascript"); scriptTag.Attributes.Add("src", scriptPath); sb.AppendLine(scriptTag.ToString()); scripts.Add(scriptPath, scriptPath); helper.ViewContext.HttpContext.Items["client-script-list"] = scripts; return new MvcHtmlString(sb.ToString()); } return MvcHtmlString.Empty; } 
+1
source

If you use partial view, you need script library links

at the top of the page add only script add as

 @Scripts.Render("~/bundles/jquery") 

then body bottom add tag

 @RenderSection("scripts", required: false) 

any other page extends the scripting section, for example

 @section scripts{ <script src="/Scripts/jquery.validation.js" type="text/javascript"></script> } 
-1
source

Source: https://habr.com/ru/post/925821/


All Articles