开发者

What are the disadvantages/problems of including scripts in the body of page rather than in the head element?

开发者 https://www.devze.com 2023-01-04 13:57 出处:网络
There开发者_JAVA技巧\'s already an entry posted regarding the pros/cons of putting javascript inside the <head> element vs. right before the close body tag (</body>).

There开发者_JAVA技巧's already an entry posted regarding the pros/cons of putting javascript inside the <head> element vs. right before the close body tag (</body>).

However I've seen sometimes developers put JavaScript code in arbitrary locations in an HTML page. It seems to be mainly due to laziness. What are the disadvantages of embedding JavaScript code in arbitrary locations of a page? There are a number of obvious disadvantages such as no caching, less reuse, etc. What other disadvantages can you think of in this regards?

Thanks in asdvance.


Read this:

http://groups.google.com/group/closure-library-discuss/browse_thread/thread/1beecbb5d6afcb41?hl=en&pli=1

The short story is that we don't want to wait for DOMContentReady (or worse the load event) since it leads to bad user experience. The UI is not responsive until all the DOM has been loaded from the network. So the preferred way is to use inline scripts as soon as possible.

<div id="my-widget">&lt;/div>  
<script>  
    initWidget(document.getElementById('my-widget'));  
</script>  

Yes, it not as easy to maintain but it leads to a better user experience. By intentionally leaving out DOMContentReady wrappers we have been able to prevent Google Apps to use on this anti pattern.

And this:

Using DOMContentReady considered anti-pattern by Google


Whenever you put a script element in a page, regardless of where it is, unless you use the defer or async attributes and the browser your visitor is using supports them, all HTML parsing comes to a full stop and control is given over to the JavaScript interpreter (waiting for the script file to download, if the script is in a separate file). This holds up the rendering of your page. So unless you have a really good reason for putting the script tag somewhere else, putting the script tag at the very bottom of your page will improve its apparent loadtime.

There can be really good reasons, of course. For instance, if the script has to use document.write to output HTML to the page (like many ad scripts do), then of course it has to be in the location where that HTML has to go. Similarly, if you have a button in your UI and you're hooking up a handler to that button that calls your script, if the script is further down in the page, there may be a window of opportunity for the user to click the button before your script is there to handle the click, either doing nothing or getting an error, either of which negatively affects the user experience.

If your page is fully functional without any script (good practice for most general-purpose websites), with the script merely enhancing the experience, put the script at the bottom. If the script is critical to the functionality of your site (perfectly acceptable practice for some sites, and certainly for many web-based applications), best to have your build process combine all of your custom JavaScript into one file, minify it, and link it in the head, so that you're holding things up as briefly as possible. (If your script relies on libraries, you can load them separately from a CDN for speed, or prepend them to your custom code, depending on your assessment of which will be faster for your users.)

That's all a speed/perceived speed argument. From a separation of concerns standpoint, make sure all of your JavaScript is in separate files (at least, separate source files; you could have a build process that mergers your JavaScript into your HTML to produce an ouput file to serve to the user without violating separation of concerns; but then you can't get caching of your JavaScript if you use it on more than one page). Once you have a separate JavaScript file, you're going to have to link to the script somewhere, I don't think it really makes a big difference from a separation of concerns standpoint where as long as you don't have script elements littered all over the HTML source.

Edit: See also David Murdoch's answer quoting Google on the value of inline script blocks for hooking up UI. I wanted to reference it but couldn't find it; he did. It's a pain because (unless you do this with a build script) it really messes up separation of concerns. On the up side, it shouldn't be that hard to do with tags and a build script...


The most obvious disadvantage to me is, if it's a framework, members aren't accessible until after it's downloaded and parsed. Consider the following scenario:

<html>
  <head>
    <script type="text/javascript">
       $(document).ready(function () { /* ... */ });
    </script>
  </head>
  <body>
    <!-- rest of content -->
    <script type="text/javascript" src="jquery.1.4.2.min.js"></script>
  </body>
</html>

Of course, you'd get a "$ is undefined" error. All code that relies on that script must follow it in execution order (unless you use timers, the defer attribute or the window.onload event).

The outweigh the disadvantages as far as I can see.


It's the same principle that CSS was created for. In the way that presentation and markup are separated using stylesheets with your HTML, functionality and markup should be separated by including your javascript externally, rather than inline with your HTML elements.

Also, less code rewriting. Seriously, who wants to write

<input type="text" onfocus="$(this).css('background', 'yellow');" />

for every input element when it is easier to write all that functionality once?

$('input[type="text"]')
    .focus(function() { $(this).css('background', 'yellow'); })
    .blur(function() { $(this).css('background', 'white'); });
0

精彩评论

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