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.
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. This, perhaps, is the reason why people don't recommend adding js to Partial View directly. In my case, it needs to be there for the plug-in and manipulation within the Partial View itself. Is there a good way to check for loaded js and prevent it from loading it again in subsequent click event?
The JavaScript and CSS files for Chosen should be included on the page when the page first loads. When the user clicks the button, make an Ajax call to include the partial. In the success callback for the AJAX request, initialize the Chosen plugin code for the dropdown lists that were just injected in the page.
Your are correct that duplicate JS and CSS files will get loaded, which is definitely something you don't want.
$.ajax(...)
.done(function(data) {
$("#foo")
.html(data)
.find("select")
.each(function() {
$(this).chosen({...});
});
});