JavaScript Advanced Programming (2) using JavaScript in HTML

Source: Internet
Author: User
Tags blank page



This chapter covers the use of <script> elements, embedded scripts and external scripts, the impact of document patterns on JavaScript, and scenarios that consider disabling JavaScript.



1.<script> Elements



The main way to insert JavaScript into an HTML page is to use the <script> element. HTML4.01 defines the following properties for <script>:



Async: Optional. Indicates that the script should be downloaded immediately, but should not interfere with other actions on the page, such as downloading additional resources or waiting for other scripts to load. Valid only for external script files.



CharSet: Optional. Represents the character set of the code that should be specified through the SRC attribute.



Defer: Optional. Indicates that the script can be deferred until the document is fully parsed and displayed before execution. Valid only for external script files.



Language: Deprecated.



SRC: Optional. Represents the external condition that contains the code to execute.



Type: Optional. Can be seen as an alternative attribute of language, a content type that represents the scripting language in which the code is written. This property is not required, and if you do not specify this property, the default value is Text/javascript.



There are two ways to use the <script> element: embed JavaScript code directly in the page and include external JavaScript files.



Embedded: When embedding JavaScript code with the <script> element, you only need to specify the type attribute for <script>. The following is where the JavaScript code is placed directly inside the element:

<script type = "text / javascript">
function sayScript ()
{
  alert ("Hi!");
}
</ script>
The JavaScript code contained inside the <script> element will be explained in order from top to bottom. Take the previous example, the interpreter will explain the definition of a function, and then save the definition in its own environment. Before the interpreter evaluates all the code inside the <script> element. The rest of the content on the page will not be loaded or displayed by the browser.

  When using <script> to embed JavaScript code, remember not to appear the "</ script>" string anywhere in the code. Because according to the rules of parsing embedded code, when the browser encounters the string "</ script>", it will think that it is the end </ script> tag. Instead, escape the character "/" to solve this problem.

External: Use the <script> element to include external JavaScript files, then the src attribute is required. This attribute points to a link to an external JavaScript file. E.g: 

<script type = "text / javascript" src = "example.js"> </ script>
In this example. The external file example.js will be loaded into the current page. The external conditions need only include the JavaScript code that is usually placed between the opening <script> and the closing </ script>.

      2. Location of the label

 According to the traditional approach, all <script> elements should be placed in the <head> element of the page, for example:

        <title> Example HTML Page </ title>
        <script type = "text / javascript" src = "exmpale1.js"> </ script>
        <script type = "text / javascript" src = "example2.js"> </ script>
    </ head>
    <body>
        <!-Put content here->
    </ body>
    </ html>
The purpose of this approach is to put all external files (including CSS files and JavaScript files) references in the same place. However, the inclusion of all JavaScript files in the <head> element of the document means that all the JavaScript code must be downloaded, parsed, and executed before the content of the page can be rendered (the browser only encounters the <body> tag) Start displaying content) For pages with a lot of JavaScript code, it will cause a significant delay in the browser when rendering the page, and the browser window during the delay will be blank. This will give users a bad experience.

Therefore, nowadays Web applications generally put all JavaScript references behind the content of the page in the <body> element, as shown in the following example:

    <! DOCTYPE html>
    <html>
    <head>
        <title> Example HTML Page </ title>
    </ head>
    <body>
        <!-Put content here->
        <script src = "jquery.min.js"> </ script>
        <script src = "example.js"> </ script>
    </ body>
    </ html>
 Before parsing the included JavaScript code, the content of the page will be completely rendered in the browser. The user also feels that the speed of opening the page is accelerated because the time for displaying a blank page in the browser window is shortened.

    3. Delay script

  defer: indicates that the script will not affect the structure of the page when it is executed. In other words, the script will be delayed until the entire page is parsed before running. Therefore, setting the defer attribute in the <script> element is equivalent to telling the browser to download immediately, but delay execution.

 

   <! DOCTYPE html>
    <html>
    <head>
        <title> Example HTML Page </ title>
        <script type = "text / javascript" defer = "defer" src = "jquery.min.js"> </ script>
        <script type = "text / javascript" defer = "defer" src = "example.js"> </ script>
 </ head>
    <body>
        <!-Put content here->
    </ body>
    </ html>
 

 

 

  In this example, although we put the <script> element in the <head> element of the document, the script contained in it will be delayed until the browser encounters the </ html> tag.

It is best to include only one deferred script, and the defer attribute only applies to external script files. Putting the deferred script at the bottom of the page is still the best option.

   4. Asynchronous script

  async: Similar to the defer attribute, both are used to change the behavior of processing scripts. async only works with external script files and tells the browser to download the file immediately. Scripts marked as async are not guaranteed to be executed in the order they are specified. E.g:

   <! DOCTYPE html>
    <html>
    <head>
        <title> Example HTML Page </ title>
        <script type = "text / javascript" async src = "jquery.min.js"> </ script>
        <script type = "text / javascript" async src = "example.js"> </ script>
 </ head>
    <body>
        <!-Put content here->
    </ body>
    </ html>
 

In the above code, the second script file may be executed before the first script file. Therefore, it is very important to ensure that the two do not depend on each other. The purpose of specifying the async attribute is to prevent the page from waiting for the two scripts to download and execute, thereby asynchronously loading other content of the page. For this reason, it is recommended that asynchronous scripts do not modify the DOM during loading.

Embed code and external files

 Although it is no problem to embed JavaScript code in HTML, it is generally considered that the best practice is to use external files to contain JavaScript code whenever possible. It has the following advantages:

   Maintainability: JavaScript throughout different HTML pages can cause maintenance problems. But keeping all JavaScript files in one folder makes maintenance much easier. Developers can concentrate on editing JavaScript code without touching HTML tags.

   Cacheable: The browser can cache all external JavaScript files linked according to specific settings. If the pages all use the same file, then this file only needs to be downloaded once. The final result can speed up the page loading speed.

<noscript> element

   How to make the page degenerate smoothly when the browser does not support JavaScript. The solution is to create a <noscript> element to display alternative content in browsers that do not support JavaScript. Only the following conditions will be displayed:

  The browser does not support scripts;

  The browser supports scripting, but scripting is disabled.

  Meet any of the above conditions, the browser will display the contents of <noscript>. In other cases, the browser will not render the content in <noscript>. Look at this example:

 

   <! DOCTYPE html>
    <html>
    <head>
        <title> Example HTML Page </ title>
        <script type = "text / javascript" defer = "defer" src = "jquery.min.js"> </ script>
        <script type = "text / javascript" defer = "defer" src = "example.js"> </ script>
 </ head>
    <body>
       <noscript>
          <p> This page requires browser support (enabled) JavaScript
       </ noscript>
    </ body>
    </ html>
 

 This page will display a message to the user if the script is invalid. In a browser with scripting enabled, users can never see it, even though it is part of the page.

 summary:

  To insert JavaScript into HTML pages, use the <script> element. Use this element to embed JavaScript into an HTML page, mixing scripts and markup; it can also include external JavaScript files. have to be aware of is:

    1. When including an external JavaScript file, the src attribute must be set to point to the URL of the corresponding file. This file can be a file on the same server as the page that contains it, or a file in any other domain.

    2. All <script> elements will be parsed according to the order in which they appear on the page. Without defer and async attributes, only after parsing the code in the previous <script> element will the parsing begin Code behind the <script> element.

    3. Because the browser will first parse the code in the <script> element that does not use the defer attribute, and then parse the following content, so the <script> element should generally be placed at the end of the page, after the main content, </ body> Front of the label.

    4. Use the defer attribute to allow the script to execute after the document is fully rendered. Delayed scripts are always executed in the order they are specified.

    5. Use the async attribute to indicate that the current script does not have to wait for other scripts or block document presentation. There is no guarantee that asynchronous scripts will be executed in the order they appear on the page.

    6. Use the <noscript> element to specify alternative content to be displayed in browsers that do not support scripting. However, when scripting is enabled, the browser will not display any content in the <noscript> element.

JavaScript advanced programming (2) Use JavaScript in HTML

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.