简体   繁体   English

MVC部分视图Javascript

[英]MVC Partial View Javascript

I have a partial view created for re-use purposes. 我创建了一个局部视图以供重用。 This partial view has a dropdownlist which uses Chosen plugin. 此局部视图有一个使用选择插件的下拉列表。 Therefore, on the partial view I reference the chosen js/css file along with some javascript code to for document ready. 因此,在部分视图上,我引用了选定的js / css文件以及一些javascript代码以准备文档。

It works as intended. 它按预期工作。 However, now I have a page which I render the partial view upon a button click event. 但是,现在我有了一个页面,该页面在按钮单击事件时呈现部分视图。 Users can click as many times as they want. 用户可以单击任意多次。

My concern is that duplicate js will load each time they click the button. 我担心的是,重复的js每次单击按钮时都会加载。 This, perhaps, is the reason why people don't recommend adding js to Partial View directly. 也许这就是人们不建议将js直接添加到Partial View的原因。 In my case, it needs to be there for the plug-in and manipulation within the Partial View itself. 就我而言,它需要在Partial View本身中用于插件和操纵。 Is there a good way to check for loaded js and prevent it from loading it again in subsequent click event? 有没有一种好的方法来检查已加载的js,并防止它在随后的click事件中再次加载?

The JavaScript and CSS files for Chosen should be included on the page when the page first loads. 首次加载页面时,应该在页面上包含用于选择的JavaScript和CSS文件。 When the user clicks the button, make an Ajax call to include the partial. 当用户单击按钮时,进行Ajax调用以包含部分内容。 In the success callback for the AJAX request, initialize the Chosen plugin code for the dropdown lists that were just injected in the page. 在AJAX请求的成功回调中,为刚插入到页面中的下拉列表初始化Chosen插件代码。

Your are correct that duplicate JS and CSS files will get loaded, which is definitely something you don't want. 正确的是,将加载重复的JS和CSS文件,这绝对是您不想要的。

$.ajax(...)
    .done(function(data) {
        $("#foo")
            .html(data)
            .find("select")
            .each(function() {
                $(this).chosen({...});
            });
    });

Extending my comment with the answer. 用答案扩展我的评论。

You can leave multiple css files, I don't think it will do any harm. 您可以保留多个CSS文件,我认为这不会造成任何危害。 As for JS files, at first you should create a wrapper file 对于JS文件,首先应创建一个包装文件

wrapper.js wrapper.js

$(function() {
      if (!$().chosen) { //we do this only if chosen is not present
         var script = document.createElement('script');
         script.type = 'text/javascript';
         script.src = 'url to yor chosen library';

         $("body").append(script);
      }     
});

And then in your view you will reference this wrapper.js file instead of your chosen library path. 然后在您的视图中,您将引用此wrapper.js文件而不是您chosen库路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM