简体   繁体   中英

Where is the best place to put JavaScript/Ajax in a document?

Apologies for the dumb sounding question, but I need the experts to clarify.

Out of the three places to put Javascript, head , $(document).ready , or body , where would the best place be to put some ajax that uses a lot of $GET functions?

For instance I am using a JavaScript function called execute_send() but I am unsure where the best place to put it would be. Below is the error:

Problem at line 67 character 22: 'execute_send' was used before it was defined. function execute_send() {

Also how does the placement affect the page loading time?

In general, unless for some reason you need it elsewhere, put all of your JS last in the body. The browser won't continue until it's parsed your JS, so it is nice to let the page load first. See http://developer.yahoo.com/performance/rules.html

As an example of when you might actually want to put JS in the head: You might have some A/B testing code that you want to run before the page even renders - in that case, the code should go in the head, because you really do want it to run as soon as possible.

As @Thom Blake said, in general the best place is at the bottom of the <body> (+1 for that) - but I'll expand on that a bit:

The reason for this is that as the browser loads the page, it has to stop loading and parse the JavaScript when it encounters it. So if you have all your scripts in the <head> for instance, there will be a delay in loading all the content in the <body>

Note that this is a delay in loading - separate from the actual execution of the script. Something like $(document).ready() deals with when the script is executed, not with when it is loaded.

Generally, all this matters because you want a web page to feel as responsive as possible, so a best practice list for JavaScript will usually be along these lines:

  1. Place all your scripts at the bottom of the <body> so that the loading of non-JS resources, such as images, is not delayed.

  2. Combine your scripts into a single file, so that the server has to make fewer requests for resources (you'll see this referred to as "minimizing HTTP requests")

  3. Minify you scripts, to reduce their total size, which speeds up loading times

  4. Put any code reliant on the DOM (eg click handlers, HTML manipulation, etc) inside $(document).ready() (or the equivalent method for the JS library in use on the page).

Same subject : whats-pros-and-cons-putting-javascript-in-head-and-putting-just-before-the-body

In the past, i experienced some jquery problems has it was not 'loader' when initialising .. this is why we decided to insert it in the <head> .

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.

For the rest of javascripts, all before the closing </body> tag.

To explain the 'Why page will load faster' : It wont.

Browsers are single threaded, so it's understandable that while a script is executing the browser is unable to start other downloads. But there's no reason that while the script is downloading the browser can't start downloading other resources. And that's exactly what newer browsers, including Internet Explorer 8, Safari 4, and Chrome 2, have done.

The difference is visible has your ressources within the <body> tag will load/show sequencialy. When the browser gets to load <script src=...js> the complete file has to be loader before the browser can fetch another ressource. So, it's an illusion, because the browser will load/di more 'visible' content before 'javascripts'.

To visualise the whole thing : firebug > Net (tab)

As stated before, $(document).ready is not a place. (For jQuery, $(document).ready simply ensures that the DOM is fully loaded (ready to manipulate) before any script is executed.) You would place your JavaScript in the <head> or the <body> .

However, putting all of your JavaScript includes and JavaScripts at the bottom of the <body> section is best for loading performance. "Progressive Rendering" and "Parallel Downloading" are blocked for everything below the scripts. If your scripts are the last thing on the page, you're not blocking anything.

This article explains it in more depth.

Example:

<html>
      <head>
        <!-- MY HEAD CONTENT - LOAD ALL CSS -->
      </head>

      <body>

        <!-- MY HTML CODE -->

            <!-- START javascript -->
            <script type="text/javascript" src="/ajax/jquery/jquery-1.6.2.min.js"></script>
            <script type="text/javascript" src="/ajax/jquery/plugins/jquery.random_plugin.js"></script>
            <script type="text/javascript" src="/includes/some_other_scripts.js"></script>
            <script type="text/javascript" language="JavaScript">
            //<![CDATA[
                $(document).ready(function(){
                    // my jQuery/JavaScript code
                });
            //]]>
            </script><!-- END javascript -->
      </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM