Implementation Methods

JavaScript can be implemented on a single page or on an entire site. As with CSS, it can be embedded in a document, or externalized from that document. Both methods are accomplished using the script element.

We’ll start with an embedded example:

    <script type="text/javascript">
      // <![CDATA[
      ... JavaScript code goes here ...
      // ]]>
    </script>

As you can see, the script element establishes the block as being a script and the MIME-type is set (using the type attribute) to be text/javascript (text/ecmascript would also be acceptable).

The // <![CDATA[ and // ]]> may be unfamiliar to you, but you can find out more about CDATA in Chapter 7. As for the //, which you see in front of each part of the CDATA designation, those are one of the ways of designating comments in JavaScript, and we are telling the script above to ignore the remainder of each of those lines.

Externalizing your JavaScript is the preferred method of implementation, as it affords you the opportunity to include the same functions or functionality on multiple pages (and you can avoid declaring the content as CDATA). Here is how you would externalize a script:

    <script type="text/javascript" src="my_script.js"></script>

In this example, we have moved our JavaScript into a separate file and simply included it in our document by calling its filename as the source (src) of the script element. You can include as many scripts as you like in this way and even combine this approach with embedded script calls, as ...

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.