Where is the best place to link to 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, or are returned using the RenderPartial or RenderAction helper methods. Partial views are commonly used to encapsulate some common display, but they may also have some client-side script functions. My javascripts have the same names as the views they are associated with.

So, if I have a partial view of UserInformation.ascx , I have the corresponding UserInformation.js file. Most of these script files register functionality for the DOM ready event, so they will not be executed immediately.

The problem is that these scripts are added to the parent views. Therefore, if a particular view uses my partial view, it also needs to add the appropriate script file. Therefore, if someone forgets to add a script to the main view, my partial view function will not work.

As for browser execution and speed (or any other problems), is it better to include all the scripts in the XHTML header element, or does it not matter if I referenced these scripts inside my partial views? So I could avoid human error by forgetting to add a script to the view? However, I may encounter the problem of linking to the same script file. Especially if the same partial part is used several times in the same representation.

Are there any differences when we refer to scripts inside HEAD or BODY elements?
Are there any doctype related issues (I use XHTML Transitional)?
What is the most common pattern?

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

+4
source share
3 answers

If possible, it is useful to place your scripts at the end of the <body> . Thus, the browser should not stop and interpret scripts until it sees all the page layout. The user sees that the page and site seem to load faster.

+1
source

IMO, the preferred place for scripts is the HEAD element, but there are no restrictions on their use in BODY. Some types of scripts, especially. those that include document.write () documents (which I try to avoid using at all costs) should actually be in BODY (although they can also be in HEAD).

I feel your pain in a registry script. But remember, the problem with placing scripts willingly in pieces of markup is not only that you may not have included the necessary script in HEAD, it can also duplicate objects that exist in other pieces that your piece (and cannot ) to know.

0
source

There will be an increase in speed if scripts link closer to the end of the body element. This is because browsers will wait for scripts to be parsed when they find them. If the script is near the end, the visual elements will be visible, and the user will at least think that everything is moving faster (even if they have to wait anyway).

0
source

Source: https://habr.com/ru/post/1306942/


All Articles