JavaScript in HTML - Java Script

Of course,it was HTML that first made use of embedded JavaScript,so the natural first discussion point is how JavaScript is used in HTML.The evolution of HTML to include JavaScript began with the introduction of tags to be used in conjunction with JavaScript, as well as the addition of new attributes for several common parts of HTML.

The <script/> tag

JavaScript is included in HTML pages by using the <script/> tag. Typically located within the <head/>tag of a page,the <script/>tag was originally defined to have one or two attributes:language that indicates the scripting language being used and,optionally, src that indicates an external JavaScript file to include in the page.The language attribute is traditionally set to JavaScript,but it can also be used to indicate the exact version of JavaScript,such as JavaScript1.3(if the language attribute is omitted,the browser defaults to the most current version of JavaScript available).

JavaScript code can be written free form within a <script/> tag, but only if the src attribute isn’t specified; when src is specified, the code inside a <script/> tag may not work(depending on the browser). Example:

This example shows both inline JavaScript code and a link to an external JavaScript file. When using the src attribute,an external JavaScript file is referenced in the same way as images and style sheets.

External file format

External JavaScript files have a very simple format.Essentially,they are just plain text files containing JavaScript code.No <script/> tags are needed inside of external files, because the <script/> tag referencing the file is present in the HTML page.This makes external JavaScript files look very similar to source code files for other programming languages.

For example, consider the following inline code:

To externalize the sayHi() function into a file named external.js, you copy the function text itself.

External file format

Then the HTML code can be updated to include the external file:

Inline code versus external files

When should you write code inline versus writing the code in an external file? Although no hard and fast rules exist about when to use either method,the general consensus is that large amounts ofJavaScript should never be included inline for a number of reasons:

  • Security—Anyone can see exactly what the code is doing just by viewing the source of the page.If a malicious developer examines the code,he might find security holes that could compromise the site or application.Additionally, copyright and other intellectual property notices can be included in external files without interrupting the flow of the page.
  • Code Maintenance—If JavaScript code is sprinkled throughout various pages,code maintenance becomes a nightmare.It is much easier to have a directory for all JavaScript files so that when a JavaScript error occurs,there is no question about where the code is located.
  • Caching—Browsers cache all externally linked JavaScript files according to specific settings, meaning that if two pages are using the same file,it is only downloaded once. This ultimately means faster loading times.Including the same code in multiple pages is not only wasteful,but also increases the page size and thus increases the download time.

Tag placement

Generally speaking,it is common to place all code and function definitions in the <head/>tag of an HTML page so that the code is fully loaded and ready for use once the body is rendered.The only code that should appear within the <body/> tag is code that calls the functions defined previously.

Whenthe <script/> tag is placed inside of the <body/> tag, the script is executed as soon as that part of the page is downloaded to the browser.This makes it possible to execute JavaScript code before the entire page is loaded.For example:

In this code, the sayHi() method is called before any text is displayed on the page,meaning that the alert pops up before the text “This is the first text the user will see.” is ever rendered. This method of calling JavaScript inside the <body/> of a page is not recommended and should be avoided whenever possible.Instead, it is recommended to use JavaScript only as an event handler in the body of a page, such as:

Here, the <input/> tag is used to create a button that calls sayHi() when clicked. The onclick attribute specifies an event handler, which is the code that responds to a given event.

Note that JavaScript begins running as soon as the page begins loading, so it is possible to call function that doesn’t exist yet. In the previous example, you can cause an error by placing the original <script/> tag after the function call:

This example causes an error because sayHi() is called before it is defined. Because JavaScript is loading top-down,the function sayHi() does not exist until the second <script/> tag is encountered. Be aware of this problem and,as mentioned previously,use events and event handlers to call your JavaScript functions.

To hide or not to hide

When JavaScript was first introduced, only one browser supported it, so concern arose over how the nonsupporting browsers would deal with the <script/> tag and the code contained within.To that end, a format was devised to hide code from older browsers (which is a phrase that can still be found in the source code of a great many Web sites on the Internet today). The following method uses HTML comments around inline code so that other browsers won’t render the code to the screen:

The first line begins an HTML comment immediately after the opening <script> tag. This works because the browser still considers the rest of that line as part of HTML, with JavaScript code beginning on the following line.Next, you see the function definition as usual.The second-to-last line is the most interesting because it starts with a JavaScript single-line comment (the two forward slashes) and then continues with the close of the HTML comment (-->). This line is still considered part of the JavaScript code, so the single-line comment notation is necessary to avoid a syntax error. However,older browsers only acknowledge the close of the HTML comment and,therefore,ignore all the JavaScript code. A browser that supports JavaScript, however,just ignores this line and continues on to the closing

</script> tag.

Although this method of code-hiding was very prevalent in the early days of the Web,it is not as necessary today. Presently,most of the popular Web browsers support JavaScript, and those that don’t often are smart enough to ignore the code on their own. It is completely up to you whether you choose to use this method,but keep in mind that using external JavaScript files inside of inline code is a much easier method of hiding code from older browsers.

The <noscript/> tag

Another concern over browsers without JavaScript is how to provide alternate content.Hiding the code was part of the solution, but developers wanted a way to specify content that should appear only if JavaScript wasn’t available.The solution came in the form of the <noscript/> tag, that can contain any HTML code (aside from <script/>). This HTML code is ignored by browsers that support JavaScript and have it enabled; any browser that doesn’t support JavaScript or has it disabled renders the content of <noscript/>. For example:

<p>Your browser doesn’t support JavaScript.If it did support JavaScript,you would see this message:

<p>This is the first text the user will see if JavaScript is enabled. If JavaScript is disabled this is the second text the user will see.</p>

In this example, the <noscript/> tag is included with a message telling the user that the browser doesn’t support JavaScript.

Changes in XHTML

Recently,with the advent of the XHTML standard (eXtensible HTML),the <script/> tag has undergone a change.Instead of the language attribute, the tag is now expected to have a type attribute to indicate the mime type of the inline code or external file being included; the mime type for JavaScript is “text/javascript”.For example:

Even though many browsers don’t fully support XHTML,most developers are now using the type attribute in place of the language attribute in anticipation of better XHTML support. Omitting the language attribute doesn’t cause any problems because, as noted earlier, all browsers default to JavaScript for the <script/> tag.

The second change in XHTML is the use of CDATA sections.CDATA sections are used in XML (and, therefore, in XHTML) to indicate text that should not be parsed as tags, allowing the use of special characters such as the less-than (<), greater-than (>), ampersand (&), and double quotes (“) without using their character entities. Consider the following code:

This is a fairly simple function, which just compares two numbers, a and b,and then displays a message indicating their relationship. In XHTML,however, this code is invalid because it uses three special characters,less-than, greater-than, and double-quote. To fix this, you must replace these characters with their XML entities, &lt;,&gt;, and &quot;, respectively:

This code raises two problems.First, developers aren’t used to writing code using XML entities. It makes the code harder to read. Second, this is actually considered a syntax error in avaScript because the interpreter has no idea what the XML entities mean. Using a CDATA section, it is possible to write JavaScript code in its normal, readable syntax. The official way to include a CDATA section is as follows:

Although this it the official way, remember that XHTML isn’t fully supported by most browsers, which raises a major problem: This is a JavaScript syntax error because most browsers don’t recognize CDATA sections yet!

The solution currently being used is a takeoff on the old “hide from older browsers” code. By using single-line JavaScript comments, you can embed the CDATA section without affecting the syntax of the code:

This code now works in browsers that don’t support XHTML as well as those that do.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Java Script Topics