Hello, tell me where it is better to connect js files in the html page

    3 answers 3

    Syntax

    <script type="тип"> ... </script> <script type="тип" src="URL"></script> 

    Attributes
    async - Loads the script asynchronously.
    defer - defer execution of the script until the entire page is loaded completely.
    language - Sets the programming language in which the script is written.
    src - Script address from an external file to import into the current document.
    type - Specifies the type of tag content.
    Closing tag
    Required.

    I want to say that you can and at the beginning but then you need to include a check for loading DOM

     window.onload = function(){} 

    or

     document.addEventListener("DOMContentLoaded", function(){}); 

      depending on logic but i connect before </body>

      here it is worth paying attention

      Async attribute

      Supported by all browsers except IE9-. The script runs completely asynchronously. That is, when detected, the browser does not stop processing the page, but quietly works on. When the script is loaded - it will be executed.

      Defer attribute

      Supported by all browsers, including the oldest IE. The script is also executed asynchronously, it does not make the page wait, but there are two differences from async.

      First, the browser ensures that the relative order of the scripts with defer will be preserved.

      That is, in this code (with async), the script that first loads will work first:

      examples

       <script src="1.js" async></script> <script src="2.js" defer></script> 
      • It is worth saying that they can be put both at once. - Qwertiy

      The best option is to include some scripts at the end.
      What for? Those that connect below will be executed as loaded HTML code.
      If they are in the <head> tag, they will be executed earlier.

      For example, you can connect libraries at the top of the page, and scripts below, the code that will be associated with the libraries.