开发者

Does it matter where JavaScript is placed on a html page?

开发者 https://www.devze.com 2023-01-08 15:20 出处:网络
I\'ve messing about with html5, I\'ve never really had a good look at JavaScript before. I\'m referencing script file like this (not in the head)

I've messing about with html5, I've never really had a good look at JavaScript before. I'm referencing script file like this (not in the head)

<script src="somthing.js"></script>

However the script only seems to work if it placed below certain elements o开发者_JS百科n the page.

Are there particular situations when it matters where javascript is placed?

Thanks in advance.


If the script isn't waiting for an onload or "ready" event of some sort, it needs to be place after the elements it references (otherwise they won't be there to find). If you're unsure, stick it just before </body>.

In this case it looks like that's exactly what's happening, it's looking for elements that haven't been added to the DOM yet. Placing the script at the bottom of the <body> is one common practice to counter this. Some alternatives are using the window.onload event to run your code, or jQuery's $(document).ready() for example (most major libraries have some equivalent of this).


If your script is acting on an element it needs to either be placed after that element on the page or set up to execute when the page is finished loading. If the script runs before the element has been added to the DOM (which occurs when it is encountered as the browser parses the page), then the script can't find the element upon which you want it to act. Placing the script after the element ensures that the element is available for it to work on. Likewise, forcing it to run after the entire page loads makes sure that all elements are available to the script.

I'd suggest that, in so far as possible, you load your scripts right before the closing </body> tag. I would also look at using a framework, like jQuery, which makes it easy to run your scripts on page load complete and wrap the code inside it's load event.


The best practice according to Yahoo's Performance Rules is to place scripts at the bottom of the page:

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.

An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.


Well we'd need to know what was in your script to tell you really, but the short answer is "yes it does matter".

Scripts (essentially) execute when encountered by the browser. A classic blunder is to make a reference to a page element in a script placed earlier in the document than the element it references - when the script is executed the element doesn't exist yet!

It is generally considered appropriate to keep scripts in the head, the solution to the above problem therefore being to attach functional code to onload event handlers.

Bonus round: a much more subtle reason script placement matters is because most browsers will single-thread downloads when they encounter a script (for security reasons and because the script can modify the download requirements for example). This is one of the reasons yahoo recommends placing scripts last in your document, but it's a controversial thing to do for a subtle benefit of perception only.


YES it does.

for example, let's just say your js code is at the top. and it is interpreted before the browser is done setting up a section of the dom tree...in this case the HTML element that you are referencing, if referenced before it is available, will produce an error saying that the element is undefined.

Another reason is the user experience. If the css is at the top, when the html is displayed all looks good, but unless the js is at the bottom, you will have to wait for it to be loaded and be ready for execution before the rest is rendered; therefore, slowing down the rate at which items on the screen are rendered.

I see it a lot. Different strokes for different browsers, but just put the js at the bottom, and css at the top and you avoid having to worry about stuff like this.


It depends on what the script is designed to do. If it is using the document.write() method, then it does matter where it is on the page. If it's trying to reference elements in the DOM, it is best put in the HEAD and have those functions that access DOM elements triggered after the page is loaded.


There are a couple of scenarios where the placement is important.

  • Assuming you have a function call foo() in your_script.js and you call it before you include your_script.js, than it simply won't work because foo() isn't defined yet.
  • If the code requires a certain element to be available (for example, a lightbox script) than it is possible that loading the code before your lightbox image elements results in the lightbox not doing anything.

So basically... it depends very much on what scripts you are running. Sometimes it will matter, other times it won't.


Yahoo actually recommends putting your scripts at the bottom. The downloading of a JS file is a blocking action which means nothing else is downloading at that time (such as images/css) By putting your scripts at the bottom the user gets the html/images/css first and actually see the page faster, and your JS downloads after to add interactivity.

Having said that, as the other posts mention, your script has to wait until the dom is ready before actually doing anything to the DOM, otherwise you'll have varied behaviour depending on when the DOM is ready.


Well, here is what I think.

If you need to execute your script, before the HTML starts the render in the clients browser then it will be better to be placed in <head> section.

And if you are executing a JavaScript code which communicates with a element in some way then the script should be placed behind that element, because if the script starts ahead then it can't find its respective element to communicate with. So it is better to placed behind element.


This is not only about where the script is placed in the page, but also when the code in the script is executed.

Script tags normally goes in the head section of the page. However, that means that no elements are loaded when the code loads, and if it executed immediately you can't access any elements. The solution to that is to use the onload event of the page. Example:

<html>
<head>
<title></title>
<script>
function init() {
  document.getElementById('message').innerHTML = 'Hello world!';
}
</script>
</head>
<body onload="init();">
<div id="message"></id>
</body>
</html>

Javascript libraries may have other methods of doing something similiar, like the ready event in jQuery.

You can place scripts in the page (although this is not what's recommended by the HTML standard), but if you need to access elements in the page from code that runs immediately, the script has to be loaded after the elements. Example:

<html>
<head>
<title></title>
</head>
<body>
<div id="message"></id>
<script>
document.getElementById('message').innerHTML = 'Hello world!';
</script>
</body>
</html>

Scripts may also be placed late in the page for performance reasons. You can keep that in mind and save it until you actally have any performance problems.


In simple terms : Make sure the element(s) the script accesses is loaded before the script starts executes. Ofcourse if you are unsure put it just before .


Your script likely attempts to operate on the DOM before it is ready. This should not be solved by moving it around, but rather by deferring execution with domready callbacks.

After that is sorted, you should aspire to keep script inside of head. It used to be a common practice to include scripts at the bottom of the page to avoid page- and request-blocking. In HTML5 such performance impacts no longer matter since you can take advantage of async attribute. It allows for the loading of JS files to be initiated without side-effects:

Traditional scripts block the HTML parser, preventing the rest of the page from being rendered until the script has been downloaded and run. Scripts using HTML5 async unblock the rest of the page so it can continue loading while the script is being downloaded. ^

0

精彩评论

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

关注公众号