Include JavaScript file in partial views

后端 未结 9 1511
别跟我提以往
别跟我提以往 2020-12-02 06:13

I am wondering what the best practice is for including javascript files inside partial views. Once rendered this will end up as a js include tag in the middle of my page\'s

9条回答
  •  伪装坚强ぢ
    2020-12-02 06:38

    So, this is kind of an old question, but I found it while trying to solve a recent issue. I asked a question and answered it here. Here is a copy of that answer. It is similar to the OP's answer, but avoids using TempData.

    One solution is to implement an Html helper extension function which will only load a script once. See below. (this can work for CSS and other included files, too).

    Implement an extension for the HtmlHelper class and a private backing class as a singleton per HttpContext.

    public static class YourHtmlHelperExtensionClass 
    {
        private class TagSrcAttrTracker
        {
            private TagSrcAttrTracker() { }
    
            public Dictionary sources { get; } = new Dictionary();
    
            public static TagSrcAttrTrackerInstance {
                get {
                    IDictionary items = HttpContext.Current.Items;
                    const string instanceName = "YourClassInstanceNameMakeSureItIsUniqueInThisDictionary";
    
                    if(!items.Contains(instanceName)) 
                        items[instanceName] = new TagSrcAttrTracker();
    
                    return items[instanceName] as TagSrcAttrTracker;
                }
            }
        }
    
        public static MvcHtmlString IncludeScriptOnlyOnce(this HtmlHelper helper, string urlOfScript) 
        {
            if(TagSrcAttrTracker.Instance.sources.ContainsKey(urlOfScript))
                return null;
    
            TagSrcAttrTracker.Instance.sources[urlOfScript] = urlOfScript;
    
            TagBuilder script = new TagBuilder("script");
            scriptTag.MergeAttribute("src", urlOfScript);
    
            return MvcHtmlString.Create(script.ToString());
        }
    }
    

    Then, separate the JavaScript and other code into separate files.

    Example .js file contents

    class MyClass{
        myFunction() {
            constructor(divId){
                this._divId = divId
            }
    
            doSomething() {
                // do something with a div with id == divId
            }
        }
    }
    

    Example .cshtml file contents for partial view

    
    
    
    Some content! Yay!
    @Html.IncludeScriptOnlyOnce("/Scripts/CustomScripts/MyPartialView.js")

    Example .cshtml file that consumes the partial view

    ...
    
        

    Here is some content!

    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_1"} }) @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_2"} }) @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_3"} })

    The partial view may have been included more than once and the JavaScript is packaged with the partial view, but the .js file is only included in the page once, hence no complaining by the browser that MyClass was declared more than once.

提交回复
热议问题