What is the best place to place src="" tag scripts in HTML?

45

I recently had a problem calling the JQuery scripts in a small php script, I usually place them after the body tag like this:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

</body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</html>

This to avoid delaying the loading of the other elements of the page.

The problem is that I was doing a kind of template with 3 php files:

  • header.php
  • menus.php
  • footer.php
  • In header I call all elements head , for example css , meta , title ; in menus I create the menu that will be visible in all the pages, and in footer I have the footer and the% tag <script> , but when I make some other pages and call some JQuery function it throws me an error:

      

    $ not defined

    The solution was to place all these scripts in header . In such a way that first these scripts are loaded and then the remaining labels.

    I have reviewed this question in English OS:

    link

    However, when external scripts are loaded asynchronously, there are times when the same error mentioned above comes up.

    My question is: What is the best location to place these tags? because so far what has fixed that problem for me is keeping them in the header. Or should I think of another way to do the template in PHP?

        
    asked by Juan Pinzón 26.09.2016 в 19:05
    source

    9 answers

    67

    First of all, the script is an HTML tag that must be included in the header or in the body, it can not be included outside, for that reason you can not access Jquery.

    You must replace:

    </body>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    

    Because of this:

    <script src="https://code.jquery.com/jquery-3.1.0.js"></script> 
    </body>
    

    What is the best place to color the script tags?

    You should avoid putting the scripts in the header. The rendering and interpretation of HTML is done as the browser finds the elements in your document HTML . Therefore, if you find a script tag in the header, you will have to wait for the browser to load the script to continue with the rendering of the page, so you would see the browser with the blank screen, behavior that one you want to avoid.

      

    Additionally, the behavior of the scripts are affected by   the use of the async and defer attributes.

    Script tag without any attributes

    When we define a label script without any attribute the HTML will be interpreted until it finds the label script , at that point the interpretation will stop and request the archivo js (if external), once that we have loaded the file then it will be executed before we continue interpreting the HTML .

    Async

    The async attribute allows the browser to download the file script asíncronamente (hence the name, surprisingly not?) and continue with the interpretation of the HTML , as soon as the download is complete it will interrupt the interpretation to begin the execution of the script and immediately afterwards it will continue with the interpretation process.

    Defer

    The attribute defer unlike async , defer (defer) the execution of script after the interpretation of HTML has ended, the download is made asynchronously as in the previous case but defer us guarantees to execute the scripts in the order in which they appear in our document, unlike async that executes them just after downloading.

    How to decide between using async or defer?

    I recommend reading link .

        
    answered by 26.09.2016 в 19:37
    10

    This is wrong:

    </body>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    

    Scripts, as a general rule, should be placed before of the body closure. However, there are particular cases where it is convenient to put them in the header.

    What is the rendering process of an HTML document?

  • Parse of the document
  • Find a script tag with an external file. 2.1 Load the script and stop loading the document until the script has been fully loaded.
  • Scripts are executed.
  • Ends the loading of the document.
  • When to use async / defer?

    Async allows you to load a script asynchronously, that is, does not stop loading the document and is executed as soon as it is loaded.

    Suppose the following scenario:

    <script async src="jquery.min.js"></script>
    <script async src="bootstrap.min.js"></script>
    

    In this case, bootstrap can run before jquery.

    Defer is also not blocking, but unlike async it respects the order of the scripts.

    When is it correct to put the scripts in the header?

    A common practice is also to put the scripts in the header with async or defer , in this way, the scripts are obtained immediately when the parsing begins but without blocking it.

        
    answered by 26.09.2016 в 19:50
    9

    For me, at this time it is better to put them before the closing of the body tag as mentioned in an answer

    Simply for a reason, async is only supported in Internet Explorer 10+ so there are many users who might have problems, apart it is a feature of HTML5 so some older browsers will also be affected.

    Of course, in some years this will not matter because users of IE probably pass to Microsoft Edge where it is already supported, including updates in other browsers, it will simply no longer be justified.

    On the other hand, if you have problems with libraries like jQuery , you should check the output of your page, surely something is executed where not.

    As I use my templates I have a section of styles and 3 for scripts , imports , ready , functions

  • imports where I add <script src ...

  • ready where there is a document.ready this to only have one always.

  • functions in case there is a function that you do not want to put inside of some js by x or and reason

  • I hope I help you

        
    answered by 26.09.2016 в 19:35
    6

    The integration of JavaScript and XHTML is very flexible, since there are at least three ways to include code JavaScript in web pages.

    Include JavaScript in the same XHTML document

    The code JavaScript is enclosed between <script> tags and is included in any part of the document. Although it is correct to include any block of code in any area of the page, it is recommended to define the JavaScript code within the document header (within the <head> tag):

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Ejemplo de código JavaScript en el propio documento</title>
    <script type="text/javascript">
      alert("Un mensaje de prueba");
    </script>
    </head>
    
    <body>
    <p>Un párrafo de texto.</p>
    </body>
    </html>
    

    In order for the resulting XHTML page to be valid, it is necessary to add the attribute type to the label <script> . The values that are included in the type attribute are standardized and for the case of JavaScript , the correct value is text/javascript .

    This method is used when defining a small block of code or when you want to include specific instructions in a specific document HTML that complete the instructions and functions that are included by default in all the documents of the website.

    The main drawback is that if you want to make a modification in the code block, it is necessary to modify all the pages that include that same block of code JavaScript .

    Define JavaScript in an external file

    JavaScript instructions can be included in an external file of type JavaScript that documents XHTML link via the label <script> . You can create all the JavaScript files that are required and each document XHTML can link as many JavaScript files as you need.

    Example:

    File codigo.js

    alert("Un mensaje de prueba");

    Document XHTML

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Ejemplo de código JavaScript en el propio documento</title>
    <script type="text/javascript" src="/js/codigo.js"></script>
    </head>
    
    <body>
    <p>Un párrafo de texto.</p>
    </body>
    </html>
    

    In addition to the type attribute, this method requires defining the src attribute, which is the one that indicates the URL corresponding to the JavaScript file that you want to link. Each label <script> can only link a single file, but on the same page you can include as many <script> tags as necessary.

    Files of type JavaScript are normal text documents with the .js extension, which can be created with any text editor such as Notepad , Wordpad , EmEditor , UltraEdit , Vi , etc.

    The main advantage of linking an external JavaScript file is that it simplifies the code XHTML of the page, that you can reuse the same code JavaScript in all the pages of the website and that any modification made in the file JavaScript is immediately reflected in all pages XHTML that link it.

    Include JavaScript in XHTML elements

    This last method is the least used, since it consists of including pieces of JavaScript within the code XHTML of the page:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Ejemplo de código JavaScript en el propio documento</title>
    </head>
    
    <body>
    <p onclick="alert('Un mensaje de prueba')">Un párrafo de texto.</p>
    </body>
    </html>
    

    The biggest drawback of this method is that it unnecessarily messes with the code XHTML of the page and complicates the maintenance of the code JavaScript . In general, this method is only used to define some events and in some other special cases, as will be seen later.

        
    answered by 27.09.2016 в 13:20
    4

    There are theories for all tastes. To me personally, I like to put them before the label </body>

    One of the reasons, is that even if it fails, the code javascript , the page will be loaded anyway, although sometimes, I had to load it in head , because otherwise the page failed me

        
    answered by 27.09.2016 в 00:08
    4

    The problem you pose is not the position of elements script , but the order of execution of the page.

    In xHTML the script elements should be placed within the head element. From HTML 5 it is less restrictive and can be placed wherever you want; it is recommended to place them as last elements, that allows that the whole DOM is loaded before trying to execute anything and makes dispensable methods like ready() .

    Using properties defer or async will not solve it, you are delaying the loading of the element they affect.

    Your problem happens because of the loading / execution order: you have some fragment of code that tries to use the jQuery alias ( $ ) before the jQuery itself loads. Put the rest of your JavaScript code after loading jQuery.

    Give us a more complete sample of your code if you can not solve it.

        
    answered by 27.09.2016 в 13:24
    3

    The best thing is always to place the "scripts" before the closing of "body" and after all your HTML content div, a, span, etc., because you usually call the elements by ID or Class and they must be loaded before they start running.

    Another thing that you should also take into account when including your scripts is to place the dependencies first, for example

    ...

    </div><! Cierre de tu último tag HTML de contenido -->
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="script-que-usa-jquery-como-dependencia.js"></script>
    </body>
    </html>
    

    With this you will avoid the message of

      

    $ not defined

    because jquery will be loading before starting to execute "script-that-use-jquery-as-dependency.js".

        
    answered by 04.01.2017 в 20:14
    3

    The question is somewhat debatable since it greatly influences what the page does when it starts.

    In my experience it is to put the .css in <head> and the .js at the end of <body> similar to the following

    <head>
    <link href="mynew.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    ... mi html
    <script src="myJavaScript.js" type="text/javascript"></script>
    <body>
    

    since the css are loaded at the beginning to give the interface to the page, and the functionality that the js are added to the end, since many times you do not need functionality when starting, in the same way to be the last one load is faster because it shows the information to the user, despite not having loaded the functionality.

    Also commented that if you need to run a function when opening the page you can include the js of that function in the head.

    I hope it helps you.

        
    answered by 05.01.2017 в 21:58
    0

    The usual thing is to organize it so that it is loaded in order even if you put 'asinc'

    <html>
    <head>
    <script>"Carga de frameworks y js internos, lo primordial
     es que la librería de jquery este en cabeza y si lo tienes en local mejor, así no dependes del estado del repositorio"</script>
    <script type="text/javascript">
            window.onload = function (){"funciones de inicio que se cargan al cargar todo el html, esto es sobre todo para funciones que toquen DOM o que dependan de el"}</script>
    </head>
    <body>Aquí dentro nada de js jamás</body>
    <script>Funciones que no requieren una carga al inicio, como .clicks/.hover y demás</script>
    </html>
    

    More or less that's how we usually organize the app around here. The essential thing is that everything you can put in an external js, inside the js folder, put it there and in the html you only write the essentials.

        
    answered by 12.12.2017 в 12:56