Is it practically good to put JS files at the bottom of webpage?

非 Y 不嫁゛ 提交于 2019-12-18 04:51:07

问题


It is widely recommended that JS files should be put at the bottom of page to allow html codes to be loaded first. In this case, visitors will see something when waiting for full load of the page. However, I think this is disadvantageous for these reasons:

  1. Modern design mainly depends on JS. This means before loading JS, the page will look ugly.

  2. If interrupting the connection during the load (not loading JS at all), visitors will miss some of the website features (probably very important); and they will not understand that this is the problem of load (to re-load the page).

  3. If the server-side script die (due to an error) at the very end of script before footer (e.g. in PHP), visitors will miss the whole page functionality (by JS); but if loading JS at the top, they will only miss the footer or half the page.

  4. If loading JS first, browser will load other stuff (like images) in parallel; but if loading JS last, it may increase the load time. Because JS files are large (e.g. JQuery and JQuery UI), and all tiny stuffs (like images) have been loaded and we are loading a large file, last in line.

UPDATE: 5. Since jQuery library should be loaded before codes; if loading the jQuery library in footer (e.g. footer.php), you cannot add custom jquery codes for different pages (within the body).

Please correct me if I'm wrong! Is putting JS files in footer still beneficial?


回答1:


Edit: I am adding another point in response to the cotton I'm seeing in peoples ears on this topic.

Additional point #5. If you are seriously concerned about handling behavior on JS-fail and by that I mean, people browsing with JS turned off, what you should be doing is embracing the notion of progressive enhancement. For instance, you could design an accordion menu to act as a flyout-menu on-hover by default, yes with CSS only, and then remove that behavior by changing key classes when JS is enabled. That way users have access to the links without JS if they should turn it off but they get the enhanced behavior when JS is working.

But what you should not be trying to handle is the absence of entire JS files on pages that are supposed to have them because the page was mangled on the back-end. Handling the unexpected is one thing, but handling the failure to finish building an HTML file before it's served should not ever be considered an acceptable scenario in production, especially if you have actual back end code in your templating language (which you shouldn't) waiting to spill out and give would-be hackers something potentially interesting to look at. Broken pages should be served as error messages.

================================

  1. Dead wrong. Any time you use JS to tweak the initial static look of your page, you're doing it wrong. Maintain that separation of concerns and your pages will be much more flexible. Using JS to tweak the STATIC styles of your pages isn't modern, it's bass-ackwards and you can tell the jQuery mobile guys I said as much. If you absolutely must support IE6 and IE7 and IE8 tell your client how much it's going to cost them to cut out rounded gradient corners all over the place if they refuse to accept anything as an alternative to absolute graceful degradation for 5% of their client-base.

  2. If your pages, with no JS beforehand are taking that long to load, you have other problems that need to be addressed. How many resources are you loading? What ungodly pre-processing is your PHP up to? I call back end or design shenanigans.

  3. Are you saying it's half-acceptable to have half a page with working JS rather than completely unacceptable? Don't let go of that client, whoever they are.

  4. jQuery, when minimized is about the size of a medium-sized JPEG.

Note: It is not entirely unacceptable to have some JS up top. Some specialized code like analytics stuff or canvas normalizers require it. But anything that doesn't need to be should be at the bottom. Every time JS is parsed, the entire page load and flow calculation process stalls out. Pushing your JS to the bottom improves perceived page load times and should also serve to provide evidence that somebody on your team needing a swift kick in the butt to figure out why their code is tanking or what could be done with their 25 megabyte png-24s that they just shrunk down rather than reformatted.




回答2:


Script tags in the header block all other requests. If you have let's say 10 tags like this:

<script src="http://images.apple.com/home/scripts/promotracker.js"></script>

...they will be executed sequentially. No other files will concurrently be downloaded. Hence they increase page load time.

Check out HeadJS here as a sample solution.




回答3:


You need to think in terms of "do I need the DOM to be ready before I execute some javascript". Basically you put script tags at the bottom of the page to basically guarantee that the DOM is ready. If you link your styling in the header, and properly style the page, you shouldn't get the "ugliness". Secondly, if you are dependent on some parts of the page to be displayed with javascript to work on DOM objects, I would use more ajax calls to prevent this problem as well. The best of both worlds. Page is loaded with what you can, and then ajax calls are getting the html to populate on other parts of the page.




回答4:


I have occasionally recommended putting Javascript at the bottom of a page (just before </body>) but only in circumstances where a novice programmer couldn't really cope with window.onload or <body onload...> and that was the easiest adaptation of their code to get it to work.

I agree with your practical disadvantages, which need to be balanced against Michael's note of the effect on load time. In most cases [I submit] loading scripts in the <head> of the page wins.




回答5:


Everybody's needs are different, lets go through your list:

1) I've never had an issue with the layout or styling of the page because of javascript. If you have your HTML & CSS in order the missing javascript will be close to invisible. You can hide elements in the css and display them with javascript when they're ready. You can use jQuery's .show(); method

here's an example:

<!DOCTYPE html>
<html>
<head>
  <style>
  div { background:#def3ca; margin:3px; width:80px;
  display:none; float:left; text-align:center; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button id="showr">Show</button><button id="hidr">Hide</button>
  <div>Hello 3,</div><div>how</div><div>are</div><div>you?</div>
<script>
$("#showr").click(function () {
  $("div").first().show("fast", function showNext() {
    $(this).next("div").show("fast", showNext);
  });
});
$("#hidr").click(function () {
  $("div").hide(1000);
});
</script>
</body>
</html>

If you still have problems you can split up your javascript into ones your site relies on and other scripts and put some in the header and some in the footer.

2) That's user error, you can't control that, but you could check if the needed functionality is there and attempt to reload it. Most plugins offer some sort of confirmation if they're running or not, so you could run a test and try to reload them.

You can also delay loading of files until the user needs them, like waiting for them to focus on a form to load validation scripts or scroll past a certain point to load the code for things below "the fold"

3) If the page dies you're going to get a half-blank page anyhow. With PHP 5 you can do better error handling with exceptions

 

if (!$result = mysql_query('SELECT foo FROM bar', $db)) {
        throw new Exception('You fail: ' . mysql_error($db));
}

and this

try
{
  // Code that might throw an exception
  throw new Exception('Invalid URL.');
}
catch (FirstExceptionClass $exception) 
{
  // Code that handles this exception
} 
catch (SecondExceptionClass $exception) 
{
  // you get the idea what i mean ;)
}

4) If you minify your script you they shouldn't be much larger than images. JQuery is 32KB minified & gziped. JQuery-UI's script is 51KB. That's not too bad, most plugins should be even smaller than that.

So I suggest you should do what you have to do to get the results you want, but search for best practices that reduce errors and excess code. There's always a better way to skin a cat...




回答6:


The reason putting JS at the bottom of the page or loading in asynchronously is recommended is that JS slows the page load down.

If some browsers downloading the JS blocks other parallel downloads, and in all browsers executing the JS blocks the UI thread and hence rendering (parsing blocks in some too).

Putting it a the bottom or loading asynchronously attempts to delay the issue until it has less impact on the visitors page load experience.

Don't forget that no matter how beautiful you page is, is it takes too long to load people won't wait and 2 /3 seconds is where it starts to cause problems.

  1. Modern design can probably depends less on JS that it ever has - yes we need polyfills still but as browsers get better then we can do more with CSS

  2. This might be true for things like Backbone.js apps, but if the lack of JS breaks the site then I'd argue the design should be different.

  3. If the server-side script dies there are perhaps other issues to worry about, there's no guarantee there's enough of the page to be useful anyway.

  4. NO! JS blocks the UI thread and in some cases downloads so the images will be delayed. Also as the JS is using connections then there are less connections available for parallel downloads.

  5. Have a look at @samsaffron's article on loading jQuery late - http://samsaffron.com/archive/2012/02/17/stop-paying-your-jquery-tax

If you can delay the JS load you should




回答7:


I'm not really that familiar with putting the scripts in the footer, but you may want to look into the various ways of telling the page to only run the JavaScript AFTER the page is fully loaded.

This opens up a couple options - you could have JS dynamically load external scripts only after the page is ready.

You can also hide some or all of the page content, and then just make it visible after the page is ready. Just make sure you hide it with JS, so that non-js browsers can still see it.

See these:

  • https://www.google.com/search?q=javascript+page+ready
  • http://api.jquery.com/ready/


来源:https://stackoverflow.com/questions/9814301/is-it-practically-good-to-put-js-files-at-the-bottom-of-webpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!