Include JavaScript file in partial views

2019-01-10 03:17发布

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 html. From my point of view this isn't a nice way of doing this. They belong in the head tag and as such should not prevent the browser from rendering the html in one go.

An example: I am using a jquery picturegallery plugin inside a 'PictureGallery' partial view as this partial view will be used on several pages. This plugin only needs to be loaded when this view is used and I don't want to have to need to know which plugins each partial view is using...

Thanks for your answers.

8条回答
Melony?
2楼-- · 2019-01-10 03:40

hejdig.

Playing around with Aspnetmvc3 I decided, for now, to just include my javascript file in the partial

<script src="@Url.Content("~/Scripts/User/List.js")" type="text/javascript"></script>

This js file is then specific for my /user/List.schtml file.

/OF

查看更多
来,给爷笑一个
3楼-- · 2019-01-10 03:42

The designers of MVC went through a lot of trouble to prevent us from using code-behinds, but by creating a file named <viewname>.aspx.cs and modify the inherits attribute of the aspx page accordingly, it is still possible to get them.

I'd say, the best place to put the include would be in the Page_Load handler in the codebehind (using Page.ClientScript.RegisterClientScriptInclude).

查看更多
登录 后发表回答