loading...

HTML5 – HTML5 Scripting: Using JavaScript and script Tag

Now let’s discuss the <script> tag in HTML5. It allows you to use the JavaScript programming language with your HTML5 content creation pipeline (markup, design, programming, and publishing). The JavaScript language is based on ECMAScript 262. It connects the inner-workings of a browser and now the HTML5 OS powering your smartphone, smartwatch, tablet, notebook, and iTV Set with HTML5 markup content definition and CSS3 stylesheet design.

In this chapter, you look at the <script> tag in HTML5, which implements advanced JavaScript content that can take your HTML5 and CSS3 content to the next level. I did this with the iTVset.com website by adding a seamless clock to the HTML5 and CSS3 in the previous chapter. I am not going to go into minute details regarding the JavaScript programming languages, because this book focuses on HTML5 markup, but we’ll look at how to bridge JavaScript and HTML5. I suggest that you visit Apress (
www.apress.com

) and check out some JavaScript titles so that you can master this area.

Using JavaScript: The HTML5 SCRIPT Tag

The <script> tag

defines client-side JavaScript assets. The <script> element (tag) contains script statements, also known as JavaScript code, or references an external JS script file. This is done with the src parameter in the <script> tag or with the <link> tag. If the src attribute is present in the <script> opening tag, then the <script> element itself is empty. Common JavaScript usage includes adding interactivity, new media asset manipulation, form validation, user interface design, and similar dynamic and advanced real-time changes of your HTML5 application content. The <script> tag parameters used in HTML5 are listed in Table 17-1.

Table 17-1. Six HTML5 <script> Tag Parameters

Script Tag Parameter

Script Tag Parameter’s Usage

async (New in HTML5)

Specifies that a JavaScript is to be executed asynchronously; this is for external scripts

charset

Specifies the character set encoding used in the external JavaScript file

defer

Specifies that a JavaScript is to be executed when the page has finished parsing; this is only for external JavaScript files

src

Defines the source file for the JavaScript

type

Defines the JavaScript Media (MIME) type

xml:space (No HTML5)

Determines preservation of whitespace (XHTML)

It’s important to include the <noscript> element for the users who have disabled JavaScript in their browser, or have a browser, or operating system, which does not support client-side Java scripting.

JavaScript Execution: Parsing Synchronization

There are several ways that external

JavaScript can be executed; before rendering your HTML5 markup and CSS3 style, after rendering the HTML5 markup and CSS3 style, and during the rendering of your HTML5 markup and CSS3 styles. Synchronization of JavaScript execution with HTML5 and CSS3 markup parsing is controlled using the parameters

in Table 17-1.

If neither the async nor the defer parameter is present, then JavaScript is the first asset fetched and executed before the browser continues parsing your markup. This “first” parameter is not shown in Table 17-1. It is simply set by not setting any parameter in the <script> tag, and so it is the default way that a JavaScript is processed (first). This is because there are often things that JavaScript does to set up an HTML5 rendering environment and document structure; therefore, JavaScript needs to be executed into memory before any other elements are rendered into system memory. This is quite logical, if you think about it from a programming standpoint, because JavaScript is processed prior to HTML5 markup, which is processed before styling!

If the new in HTML5 async parameter is present inside of the <script> tag, then a script is executed asynchronously with the rest of the page. This means that a script is executed while the page in the process of parsing the HTML5 tags and applying the CSS3 styles to those tags.

If an async parameter is not present in the <script> tag and the defer parameter is instead present, then the script can only be executed when the page has finished parsing; that is, the script is paused or held back from executing until the CSS and HTML5 markup are fully applied to your document (browser) or application (operating system).

JavaScript Formats: MIME Type and Character Set

The other parameters in Table 17-1 handle data formats, which define the JavaScript code itself. The JavaScript MIME Type

(now called a Media Type) should be one of these following combinations: text/jscript, text/javascript, or text/ecmascript. Any of these types will work across all of the popular browsers and OSes that are widely used today (Mozilla Firefox, Google Chrome, Apple Safari, and Opera). The most often utilized of these three is the text/javascript MIME type, as it most clearly and simply defines the contents of the .JS file.

If you are creating an application, you would substitute the word text with the word application. If you are interested in seeing the complete list of media types, visit this URL:

http://www.iana.org/assignments/media-types/media-types.xhtml

These following three are valid

commonly used MIME Types as well: application/x-javascript, application/ecmascript, and, application/javascript.

In HTML5, the character set

is typically designated UTF-8, unless you are in a country that uses a custom character set, in which case you use UFT-16 that supports non-Roman characters, such as Asian characters.

In-Line JavaScript Code: Using the SCRIPT Tag

Since I already

showed you how to externalize a JavaScript code asset in Chapter 4, let’s look at how to use a <script> tag to add the JavaScript logic to run the clock that is referenced in the <canvas text/javascript” charset=”UTF-8″>
var hour_hand=null, minute_hand=null, second_hand=null, ctx=null,
    degrees=0, clock_face=null, clock_face=null, HEIGHT=500, WIDTH=500;
function init_itv() {
var canvas = document.getElementById(‘clock’);
  if(canvas.getContext(‘2d’) )       {
    ctx = canvas.getContext(‘2d’);
    hour_hand = new Image();
    hour_hand.src = ‘hour_hand.png’;
    minute_hand = new Image();
    minute_hand.src = ‘minute_hand.png’;
    second_hand = new Image();
    second_hand.src = ‘second_hand.png’;
    clock_face = new Image();
    clock_face.src = ‘clock_face.png’;
    clock_face.onload = imgLoaded;    }
  else                              {
    alert(“Canvas not supported!”); }
}
function clearCanvas() { ctx.clearRect(0, 0, HEIGHT, WIDTH); }
function imgLoaded()   { setInterval(draw, 500);             }
function getRequiredMinuteAngle(currentTime) {
  return Math.floor(((360/60) * currentTime.getMinutes()),0); }
function getRequiredHourAngle(currentTime)   {
  return Math.floor(((360/12) * currentTime.getHours()),0);   }
function getRequiredSecondAngle(currentTime) {
  return Math.floor(((360/60) * currentTime.getSeconds()),0); }
function draw()  {
  var currentTime = new Date();
  clearCanvas();
  ctx.drawImage(clock_face, 0, 0);
  ctx.save();
  ctx.translate(HEIGHT/2, WIDTH/2);
  rotateAndDraw(minute_hand, getRequiredMinuteAngle(currentTime));
  rotateAndDraw(hour_hand, getRequiredHourAngle(currentTime));
  rotateAndDraw(second_hand, getRequiredSecondAngle(currentTime));
  ctx.restore();    
}
function rotateAndDraw(image, angle)  {
  ctx.rotate(angle * (Math.PI / 180));
  ctx.drawImage(image, 0-HEIGHT/2, 0-WIDTH/2);
  ctx.rotate(-angle * (Math.PI / 180));
}
</script>

Global variables

accessed by all of the functions in the <script> tag are declared first at the top, and local variables are declared at the top (inside) of each function. If you want to learn JavaScript, be sure to get a good JavaScript title from Apress because this book focuses on HTML5 markup only and doesn’t cover JavaScript or CSS3 in any significant detail.

Figure 17-1 shows the clock JavaScript running inside a <canvas> tag (covered in Chapter 19) and referenced using the id parameter inside a canvas tag like the <canvas >.

Figure 17-1. JavaScript document.getElementById(‘clock’); wired to <canvas > HTML5 element to create iTVset.com clock

As you can see in

the <script> HTML5 markup, this time I am not using the “hide JS from non-supporting parsing engines” convention that I mentioned earlier in the book. Let’s discuss why that is next, as browsers and operating systems become more advanced and 100% HTML5 and HTML 5.1 this becomes less and less necessary to do, and in some cases, less and less desirable.

Hiding JavaScript: To Do or Not to Do?

When HTML browsers first became available, not all of them supported JavaScript, just as not all of them support WebGL2 (see Chapter 19) now. There used to be a convention of hiding the JavaScript inside of the <script> tag with HTML comments, so the JavaScript (external or in-line) element appeared to be empty to parsing engines that did not understand that element. HTML engines that did understand JavaScript would ignore these comments and process compile and execute) the JavaScript code correctly. Markup is parsed, whereas code is compiled and executed (or processed, to use a single term).

HTML Comments: Use <!– and –> to Hide JS Code

The convention that has been in place for well over a decade is to hide JavaScript code in HTML comments, like this:

<script>
        <!--
             JAVASCRIPT CODE
         -->
</script>

There is now discussion in the HTML5 community that this is no longer necessary or even desirable, due to the acceptance of JavaScript as HTML’s defacto standard language and because there are so many different versions of XHTML and HTML that would parse and potentially misinterpret comments and the symbols. The current consensus seems to be to vacate this practice and not use any comments in the script.

XHTML Comments: Use <!– and –> to Hide JS Code

Some discussion

of this convention suggests that to support XHTML correctly, you should use a different form of commenting that involves the [CDATA [code-here] ] code encapsulation approach inside a different (XML-centric) type of commenting convention. This looks like the following:

<script>
        //<![CDATA[
                   JAVASCRIPT CODE
        //]]>
</script>

My take on all of this is that if you are developing for HTML5 (which is now legacy code, as you’ll see in Chapter 23) or HTML 5.1, you should not worry about XHTML 1.x or HTML 2/3/4 parsing engines. They are too ancient to worry about supporting due to a

widespread

proliferation of affordable HTML5 devices.

Summary

This chapter discussed the <script> tag, which allows you to use JavaScript code with your HTML5 and CSS3 markup. The next chapter looks at the HTML5 cascading style sheet <style> tag.

Comments are closed.

loading...