Jump to content

JavaScript/JavaScript within HTML

From Wikibooks, open books for an open world



The language JavasScript was originally introduced to run in browsers and handle the dynamic aspects of user interfaces, e.g., validation of user input, modifications of page content (DOM) or appearance of the user interface (CSS), or any event handling. This implies that an interconnection point from HTML to JS must exist. The HTML element <script> plays this role. It is a regular HTML element, and its content is JS.

The <script> element may appear almost anywhere within the HTML file, within <head> as well as in <body>. There are only a few criteria for choosing an optimal place; see below.

Internal vs. external JavaScript

[edit | edit source]

The <script> element either contains JS code directly, or it points to an external file resp. URL containing the JS code through its src attribute. The first variant is called Internal JavaScript or Inline JavaScript, the second External JavaScript.

In the case of Internal JavaScript the <script> element looks like:

<script>
  // write your JS code directly here. (This line is a comment in JS syntax)
  alert("Hello World!");
</script>

Internal scripting has the advantage that both your HTML and your JS are in one file, which is convenient for quick development. This is commonly used for temporarily testing out some ideas, and in situations where the script code is small or specific to that one page.

For the External JavaScript the <script> element looks like:

<!--  point to a file or to a URL where the code is located. (This line is a comment in HTML syntax) -->
<script src="myScript.js"></script>
<script src="js/myScript2.js"></script>
<script src="https://example.com/dist/js/externallib.js"></script>
<script src="https://example.com/dist/js/externallib.min.js"></script>

<!-- although there is nothing within the script element, you should consider that the HTML5 spec  -->
<!-- doesn't allow the abbreviation of the script element to: <script src="myScript.js" />         -->

Separate Files for Javascript Code

[edit | edit source]

Having your JS in a separate file is recommended for larger programs, especially for such which are used on multiple pages. Furthermore, such splits support the pattern of Separation of Concerns: One specialist works on HTML, and another on JS. Also, it supports the division of the page's content (HTML) from its behavior (JS).

Overall, using External scripting is considered a best practice for software development.

Remote Code Injection vs. Local Library

[edit | edit source]

With the example

<script src="https://example.com/dist/js/externallib.min.js"></script>

you can inject remotely maintained code from the server https://example.com in your local web project. Remote code updates may break your local project or unwanted code features may be injected into your web project. On the other hand, centralized maintained and updated libraries serve your project due to bugfixes that are automatically updated in your project when the library is fetched again from the remote server.

Minified vs. Non-Minified Code

[edit | edit source]

Minified Javascript code compresses the source code e.g. by shorting comprehensive variables like vImage into a single character variable a. This reduces significantly the size of the library and therefore reduces network traffic and response time until the web page is ready. For development and learning it might be helpful to have the uncompressed libraries locally available.

External JavaScript

[edit | edit source]

For more detailed information you can refer to MDN [1].

The src attribute

[edit | edit source]

Adding src="myScript.js" to the opening script tag means that the JS code will be located in a file called myScript.js in the same directory as the HTML file. If the JS file is located somewhere else, you must change the src attribute to that path. For example, if it is located in a subdirectory called js, it reads src="js/myScript.js".

The type attribute

[edit | edit source]

JS is not the only scripting language for Web development, but JS is the most common one on client-side (PHP runs on server-side). Therefore it's considered the default script type for HTML5. The formal notation for the type is: type="text/javascript". Older HTML versions know a lot of other script types. Nowadays, all of them are graded as legacy. Some examples are: application/javascript, text/javascript1.5, text/jscript, or text/livescript.

In HTML5, the spec says that - if you use JS - the type attribute should be omitted from the script element [2], for Internal Scripting as well as for External Scripting.

<!-- Nowadays the type attribute is unnecessary -->
<script type="text/javascript">...</script>

<!-- HTML5 code -->
<script>...</script>

The async and defer attributes

[edit | edit source]

Old browsers use only one or two threads to read and parse HTML, JS, CSS, ... . This may lead to a bad user experience (UX) because of the latency time when loading HTML, JS, CSS, images, ... sequentially one after the next. When the page loads for the first time, the user may have the impression of a slow system.

Current browsers can execute many tasks in parallel. To initiate this parallel execution with regards to JS loading and execution, the <script> element can be extended with the two attributes async and defer.

The attribute async leads to asynchronous script loading (in parallel with other tasks), and execution as soon as it is available.

<script async src="myScript.js"></script>

defer acts similar. It differs from async in that the execution is deferred until the page is fully parsed.

<script defer src="myScript.js"></script>

Location of <script> elements

[edit | edit source]

The script element may appear almost anywhere within the HTML file. But there are, however, some best practices for speeding up a website [3]. Some people suggest to locate it just before the closing </body> tag. This speeds up downloading, and also allows for direct manipulation of the Document Object Model (DOM) while it is rendered. But a similar behavior is initiated by the above-described async and defer attributes.

<!DOCTYPE html>
<html>
<head>
  <title>Example page</title>
</head>
<body>
  <!-- HTML code goes here -->
  <script src="myScript.js"></script>
</body>
</html>

The <noscript> element

[edit | edit source]

It may happen that people have deactivated JS in their browsers for security or other reasons. Or, they use very old browsers which are not able to run JS at all. To inform users in such cases about the situation, there is the <noscript> element. It contains text that will be shown in the browser. The text shall explain that no JS code will be executed.

<!DOCTYPE html>
<html>
<head>
  <title>Example page</title>
  <script>
    alert("Hello World!");
  </script>
  <noscript>
    alert("Sorry, the JavaScript part of this page will not be executed because JavaScript is not running in your browser. Is JavaScript intentionally deactivated?");
  </noscript>
</head>
<body>
  <!-- HTML code goes here -->
</body>
</html>

JavaScript in XHTML files

[edit | edit source]

XHTML uses a stricter syntax than HTML. This leads to small differences.

First, for Internal JavaScript it's necessary that the scripts are introduced and finished with the two additional lines shown in the following example.

<script>
  // <![CDATA[
  alert("Hello World!");
  // ]]>
</script>

Second, for External JavaScript the type attribute is required.

Reference

[edit | edit source]