Is it bad practice to embed JavaScript into the body of HTML?

前端 未结 17 2400
梦谈多话
梦谈多话 2020-12-13 01:44

A team that I am working on has gotten into the habit of using

17条回答
  •  有刺的猬
    2020-12-13 01:58

    I prefer to put references to external scripts into the head, and scripts that start things up and initialize widgets and whatnot into the body.

    An issue that's very easy to run into is that a script element in the body cannot access elements that come after it. Also, a related nasty browser compatibility issue is the fact that IE doesn't allow script elements to modify the element they're in. So if you have this:

    IE is not going to like your page. Old versions of IE used to give very cryptic error messages for this or even blank the entire page, but IE8 seems to give a descriptive error message.

    As long as you make sure that your scripts only access DOM that's safe to access, I don't think it's evil to put script elements into the body. In fact, IMHO, putting scripts that initialize widgets after the related elements can be more readable than putting everything in one place (and I believe this might also make them run earlier, which makes stuff jump around less as the page loads).

提交回复
热议问题