开发者

Where is the best place to reference javascripts in an XHTML document

I have an Asp.net MVC project that modestly uses jQuery scripts. My views also display partial views in them, either returned using RenderPartial or RenderAction helper methods. Partial views are usually used to encapsulate some common display but they may as well have some client-side script functionality. My javascripts have the same names as views to which they are related.

So if I have a partial view UserInformation.ascx I have a matching UserInformation.js file. Most of these script files register functionality for DOM ready event so they won't be executed immediately.

The problem is, that these scripts are added to parent views. So if a certain view uses my partial view it also needs to add its matching script file. So if someone forgets to add the script to main view, my partial view functionality won't work.

In terms of browser execution and speed (or any other issues) is it better to include all scripts in XHTML head element or is it irrelevant if I'd reference these scripts inside my partial views? This way I could avoid human error of forgetting to add the script to the view? I could get a problem of referencing the same script file multiple times though. Especially if th开发者_如何学JAVAe same partial is used several times on the same view.

Are there any differences when we reference scripts inside HEAD or BODY elements?

Are there any doctype related issues (I'm using XHTML Transitional)?

What is the most common pattern?

It would be nice to have some sort of script registration functionality in Asp.net MVC that would prevent me from loading the same script file multiple times...


If possible, it's actually beneficial to place your scripts at the end of the <body> tag. That way, the browser doesn't have to stop and interpret the scripts until after it's seen all the page markup. The user sees the page and the site seems to load faster.


IMO, the preferred place for scripts is in the HEAD element, but there are no prohibitions against using them in the BODY. Certain types of scripts, esp. those including document.write() statements (which I try to avoid using at all costs), actually need to be in the BODY (although those can be in the HEAD as well).

I feel your pain about a script registry. But remember, the problem with placing scripts willy-nilly in chunks of markup isn't only that you may not have included a necessary script in the HEAD, it's also that you may be duplicating objects that exists in other chunks that your chunk doesn't (and can't) know about.


There will be a perceived increase of speed if scripts are referenced near the end of the body element. This is because browsers will wait to parse scripts when they find them. If the script is near the end then visual elements will be visible, and the user will at least think things are moving faster (even if they have to wait either way).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜