• 2 JavaScript in HTML


    1 The " anywhere in your code. For example, the following code causes an error when loaded into a browser

    <script>
     	function sayScript() {
     		console.log("script>");
     	}
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Because of the way that inline scripts are parsed, the browser sees the string "" as if it were the closing tag. This problem can be avoided easily by escaping the “/” character, as in this example:

    <script>
     	function sayScript() {
     		console.log("<\/script>");
     	}
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    The changes to this code make it acceptable to browsers and won’t cause any errors.

    To include JavaScript from an external file, the src attribute is required. The value of src is a URL linked to a file containing JavaScript code, like this:

    <script src="example.js">script>
    
    • 1

    In this example, an external file named example.js is loaded into the page. The file itself need only contain the JavaScript code that would occur between the opening tags. As with inline JavaScript code, processing of the page is halted while the external file is interpreted. (There is also some time taken to download the file.) In XHTML documents, you can omit the closing tag, as in this example:

    <script src="example.js"/>
    
    • 1

    This syntax should not be used in HTML documents because it is invalid HTML and won’t be handled properly by some browsers, most notably Internet Explorer.

    NOTE
    By convention, external JavaScript files have a .js extension. This is not a requirement because browsers do not check the file extension of included JavaScript files. This leaves open the possibility of dynamically generating JavaScript code using a server-side scripting language, or for in-browser transpilation into JavaScript from a JavaScript extension language such as
    TypeScript or React’s JSX. Keep in mind, though, that servers often use the file extension to determine the correct MIME type to apply to the response. If you don’t use a .js extension, double-check that your server is returning the correct MIME type.

    It’s important to note that a tags. If both are provided, the script file is downloaded and executed while the inline code is ignored.

    One of the most powerful and most controversial parts of the