Simply JavaScript: The Three Layers of the Web

    Kevin Yank
    Kevin Yank
    Share

    “Once upon a time, there was … ‘A king!’ my little readers will say right away. No, children, you are wrong. Once upon a time there was a piece of wood …”
    The Adventures of Pinocchio

    You can do a lot without JavaScript. Using Hypertext Markup Language (HTML — throughout this article, we’ll refer to HTML and XHTML as just HTML. Which you choose is up to you, and doesn’t have a much to do with JavaScript. In case it matters to you, the HTML code we’ll present in this article will be valid XHTML 1.0 Strict), you can produce complex documents that intricately describe the content of a page — and that content’s meaning — to the minutest detail. In this chapter from the new Simply Javascript (you can also download this article, along with two others, as a PDF), I’ll show you that by using Cascading Style Sheets (CSS), you can present that content in myriad ways, with variations as subtle as a single color, as striking as replacing text with an image.

    No matter how you dress it up, though, HTML and CSS can only achieve an animatronic monstrosity that wobbles precariously when something moves nearby. It’s when you wheel in the JavaScript that you really can breathe life into your Pinocchio, lifting you as its creator from humble shop clerk to web design mastery!

    But whether your new creation has the graceful stride of a runway model, or the shuffling gait of Dr. Frankenstein’s monster, depends as much on the quality of its HTML and CSS origins as it does on the JavaScript code that brought it to life.

    Before we learn to work miracles, therefore, let’s take a little time to review how to build web sites that look good both inside and out, and see how JavaScript fits into the picture.

    Keep ’em Separated

    Not so long ago, professional web designers would gleefully pile HTML, CSS, and JavaScript code into a single file, name it index.html (or default.htm, if they had been brainwashed by Microsoft), and call it a web page. I’ve conceptualized this as something like Figure 1. You can still do this today, but be prepared for your peers to call it something rather less polite.

    Figure 1. A single-file mess

    Somewhere along the way, web designers realized that the code they write when putting together a web page does three fundamental things:

    • It describes the content of the page.
    • It specifies the presentation of that content.
    • It controls the behavior of that content.

    They also realized that keeping these three types of code separate, as depicted in Figure 2, “Separation of concerns,” made their jobs easier, and helped them to make web pages that work better under adverse conditions, such as when users have JavaScript disabled in their browsers.

    Computer geeks have known about this for years, and have even given this principle a geeky name: the separation of concerns.

    Figure 2. The separation of concerns

    Now, realizing this is one thing, but actually doing it is another — especially if you’re not a computer geek. I am a computer geek, and I’m tempted to do the wrong thing all the time.

    I’ll be happily editing the HTML code that describes a web page’s content, when suddenly I’ll find myself thinking how nice that text would look if it were in a slightly different shade of gray, if it were nudged a little to the left, and if it had that hee-larious photocopy of my face I made at the last SitePoint office party in the background. Prone to distraction as I am, I want to make those changes right away. Now which is easier: opening up a separate CSS file to modify the page’s style sheet, or just typing those style properties into the HTML code I’m already editing?

    Like behaving yourself at work functions, keeping the types of code you write separate from one another takes discipline. But once you understand the benefits, you too will be able to summon the willpower it takes to stay on the straight and narrow.

    Three Layers

    Keeping different kinds of code as separate as possible is a good idea in any kind of programming. It makes it easier to reuse portions of that code in future projects, it reduces the amount of duplicate code you end up writing, and it makes it easier to find and fix problems months and years later.

    When it comes to the Web, there’s one more reason to keep your code separate: it lets you cater for the many different ways in which people access web pages.

    Depending on your audience, the majority of your visitors may use well-appointed desktop browsers with cutting-edge CSS and JavaScript support, but many might be subject to corporate IT policies that force them to use older browsers, or to browse with certain features (like JavaScript) disabled.

    Visually impaired users often browse using screen reader or screen magnifier software, and for these users your slick visual design can be more of a hindrance than a help.

    Some users won’t even visit your site, preferring to read content feeds in RSS or similar formats if you offer them. When it comes time to build these feeds, you’ll want to be able to send your HTML content to these users without any JavaScript or CSS junk.

    The key to accommodating the broadest possible range of visitors to your site is to think of the Web in terms of three layers, which conveniently correspond to the three kinds of code I mentioned earlier. These layers are illustrated in Figure 3, “The three layers of the Web.”

    Figure 3. The three layers of the Web

    When building a site, we work through these layers from the bottom up:

    1. We start by producing the content in HTML format. This is the base layer, which any visitor using any kind of browser should be able to view.

  • With that done, we can focus on making the site look better, by adding a layer of presentation information using CSS. The site will now look good to users able to display CSS styles.
  • Lastly, we can use JavaScript to introduce an added layer of interactivity and dynamic behavior, which will make the site easier to use in browsers equipped with JavaScript.
  • If we keep the HTML, CSS, and JavaScript code separate, we’ll find it much easier to make sure that the content layer remains readable in browsing environments where the presentation and/or behavior layers are unable to operate. This “start at the bottom” approach to web design is known in the trade as progressive enhancement.

    Let’s look at each of these layers in isolation to see how we can best maintain this separation of code.

    HTML for Content

    Everything that’s needed to read and understand the content of a web page belongs in the HTML code for that page — nothing more, nothing less. It’s that simple. Web designers get into trouble when they forget the K.I.S.S. principle (Keep It Simple, Stupid) and cram non-content information into their HTML code, or alternatively move some of the page’s content into the CSS or JavaScript code for the page.

    A common example of non-content information that’s crammed into pages is presentational HTML — HTML code that describes how the content should look when it’s displayed in the browser. This can include old-fashioned HTML tags like <b>, <i>, <u>, <tt>, and <font>:

    <p>Whatever you do, <a href="666.html"><font color="red">don't
    click this link</font></a>!</p>

    It can take the form of inline CSS applied with the style attribute:

    <p>Whatever you do, <a href="666.html" style="color: red;">don't
    click this link</a>!</p>

    It can also include the secret shame of many well-intentioned web designers: CSS styles applied with presentational class names:

    <p>Whatever you do, <a href="666.html" class="red">don't click
    this link</a>!</p>

    Presentational Class Names? If that last example looks okay to you, you’re not alone, but it’s definitely bad mojo. If you later decide you want that link to be yellow, you’re either stuck updating both the class name and the CSS styles that apply to it, or living with the embarrassment of a class named “red” that is actually styled yellow. That’ll turn your face yellow — er, red!

    Rather than embedding presentation information in your HTML code, you should focus on the reason for the action — for example, you want a link to be displayed in a different color. Is the link especially important? Consider surrounding it with a tag that describes the emphasis you want to give it:

    <p>Whatever you do, <em><a href="evil.html">don't click this
    link</a></em>!</p>

    Is the link a warning? HTML doesn’t have a tag to describe a warning, but you could choose a CSS class name that conveys this information:

    <p>Whatever you do, <a href="evil.html" class="warning">don't
    click this link</a>!</p>

    You can take this approach too far, of course. Some designers mistake tags like <h1> as presentational, and attempt to remove this presentational code from their HTML:

    <p class="heading">A heading with an identity crisis</p>

    Really, the presentational information that you should keep out of your document is the font, size, and color in which a heading is to be displayed. The fact that a piece of text is a heading is part of the content, and as such should be reflected in the HTML code. So this code is perfectly fine:

    <h1>A heading at peace with itself</h1>

    In short, your HTML should do everything it can to convey the meaning, or semantics of the content in the page, while steering clear of describing how it should look. Web standards geeks call HTML code that does this semantic markup.

    Writing semantic markup allows your HTML files to stand on their own as meaningful documents. People who, for whatever reason, cannot read these documents by viewing them in a typical desktop web browser will be better able to make sense of them this way. Visually impaired users, for example, will be able to use assistive software like screen readers to listen to the page as it’s read aloud, and the more clearly your HTML code describes the content’s meaning, the more sense tools like these will be able to make of it.

    Best of all, however, semantic markup lets you apply new styles (presentation) and interactive features (behavior) without having to make many (or, in some cases, any!) changes to your HTML code.

    CSS for Presentation

    Obviously, if the content of a page should be entirely contained within its HTML code, its style — or presentation — should be fully described in the CSS code that’s applied to the page.

    With all the work you’ve done to keep your HTML free of presentational code and rich with semantics, it would be a shame to mess up that file by filling it with snippets of CSS.

    As you probably know, CSS styles can be applied to your pages in three ways:

    inline styles:
    <a href="evil.html" style="color: red;">
    Inline styles are tempting for the reasons I explained earlier: you can apply styles to your content as you create it, without having to switch gears and edit a separate style sheet. But as we saw in the previous section, you’ll want to avoid inline styles like the plague if you want to keep your HTML code meaningful to those who cannot see the styles.

    embedded styles:
    <style type="text/css">
    .warning {
    color: red;
    }

    </style>
    &#8942;
    <a href="evil.html" class="warning">

    Embedded styles keep your markup clean, but tie your styles to a single document. In most cases, you’ll want to share your styles across multiple pages on your site, so it’s best to steer clear of this approach as well.

    external styles:
    <link rel="stylesheet" href="styles.css" />
    &#8942;
    <a href="evil.html" class="warning">
    Example 1.1. styles.css

    .warning {
    color: red;
    }

    External styles are really the way to go, because they let you share your styles between multiple documents, they reduce the amount of code browsers need to download, and they also let you modify the look of your site without having to get your hands dirty editing HTML.

    But you knew all that, right? We’re dealing with a JavaScript book, after all, so let’s talk about the JavaScript that goes into your pages.

    JavaScript for Behavior

    As with CSS, you can add JavaScript to your web pages in a number of ways.

    You can embed JavaScript code directly in your HTML content:
    <a href="evil.html" onclick="JavaScript code here">

    You can include JavaScript code at the top of your HTML document in a <script> tag:
    <script type="text/javascript"><!--//--><![CDATA[//><!--
    JavaScript code here
    //--><!]]></script>
    &#8942;
    <a href="evil.html" class="warning">

    CDATA? If you’re wondering what all that gobbledygook is following the <script> tag and preceding the </script> tag, that’s what it takes to legitimately embed JavaScript in an XHTML document without confusing web browsers that don’t understand XHTML (like Internet Explorer).

    If you write your page with HTML instead of XHTML, you can get away with this much simpler syntax:
    <script type="text/javascript">
    JavaScript code here
    </script>

    You can put your JavaScript code in a separate file, then link to that file from as many HTML documents as you like:
    <script type="text/javascript" src="script.js"></script>
    &#8942;
    <a href="evil.html" class="warning">
    Example 1.2. script.js (excerpt)
    JavaScript code here

    Guess which method you should use.

    Writing JavaScript that enhances usability without cluttering up the HTML document(s) it is applied to, without locking out users that have JavaScript disabled in their browsers, and without interfering with other JavaScript code that might be applied to the same page, is called unobtrusive scripting.

    Unfortunately, while many professional web developers have clued in to the benefits of keeping their CSS code in separate files, there is still a lot of JavaScript code mixed into HTML out there. By showing you the right way to use JavaScript, we hope to help change that.

    The Right Way

    So, how much does all this stuff really matter? After all, people have been building web sites with HTML, CSS, and JavaScript mixed together for years, and for the majority of people browsing the Web, those sites have worked.

    Well, as you come to learn JavaScript, it’s arguably more important to get it right than ever before. JavaScript is by far the most powerful of the three languages that you’ll use to design web sites, and as such it gives you unprecedented freedom to completely mess things up.

    As an example, if you really, really like JavaScript, you could go so far as to put everything — content, presentation, and behavior — into your JavaScript code. I’ve actually seen this done, and it’s not pretty — especially when a browser with JavaScript disabled comes along.

    Even more telling is the fact that JavaScript is the only one of these three languages that has the ability to hang the browser, making it unresponsive to the user.

    Therefore, we’ll do our darnedest to show you the right way to use JavaScript, not just because it keeps your code tidy, but because it helps to keep the Web working the way it’s meant to — by making content accessible to as many people as possible, no matter which web browser they choose to use.

    JavaScript Libraries

    As I mentioned, one of the benefits of keeping different kinds of code separate is that it makes it easier to take code that you’ve written for one site and reuse it on another. Certain JavaScript maniacs (to be referred to from this point on as “people”) have taken the time to assemble vast libraries of useful, unobtrusive JavaScript code that you can download and use on your own web sites for free.

    Throughout Simply Javascript, we build each of the examples from scratch — all of the JavaScript code you need can be found right there. Since there isn’t always time to do this in the real world, however, and because libraries are quickly becoming an important part of the JavaScript landscape, we’ll also look at how the popular JavaScript libraries do things whenever the opportunity presents itself.

    Here are the libraries that we use in the book:

    Not All Libraries are Created Equal Watch out for sites offering snippets of JavaScript code for you to copy and paste into your web pages to achieve a particular effect. There is a lot of free code out there, but not all of it is good. In general, the good libraries come in the form of JavaScript (.js) files that you can link into your pages unobtrusively, instead of pasting JavaScript directly into your HTML code. If you don’t feel confident to judge whether a particular JavaScript library is good or bad, ask for some advice in the SitePoint Forums, or just stick with the libraries I just mentioned — they’re all very good.

    Let’s Get Started!

    Enough preaching — you checked out this article to learn JavaScript, right? Clean HTML and CSS are nice and all, but it’s time to take the plunge into the third layer of the Web: behavior. The chapters of Simply Javascript that follow the one from which this article is reproduced deal in greater depth with this topic — and because we’re feeling generous, we’ve decided to throw them in for your delectation! So don’t forget to download this chapter as a PDF, as well as Chapter 2: Programming with JavaScript and Chapter 3: Document Access.

    In Chapter 2, you’ll learn that as JavaScript is a programming language, you must get your head around the way computer programs work — which to some extent means learning to think like a computer — in order to use it most effectively. The simple concepts introduced in this chapter — statements, variables, expressions, loops, functions, and objects — are the building blocks for every JavaScript program you’ll ever write.

    And Chapter 3? While certain people enjoy writing JavaScript code for its own sake, you wouldn’t want to run into them in a dark alley at night. As a well-adjusted web developer, you’ll probably want to use JavaScript to make changes to the contents of your web pages using the Document Object Model (DOM). Lucky for you, we wrote a whole chapter to show you how!

    Then, of course, there’s more…

    Get ready to start using some cool (and unobtrusive) JavaScript!

    Frequently Asked Questions (FAQs) about JavaScript Layers

    What are JavaScript layers and why are they important?

    JavaScript layers are essentially different levels of JavaScript code that interact with each other to create a dynamic web page. They are important because they allow developers to separate different functionalities of a web page into distinct sections. This makes the code easier to manage, debug, and update. Moreover, using layers can enhance the user experience by making web pages more interactive and responsive.

    How do I add a layer in JavaScript?

    Adding a layer in JavaScript involves creating a new layer object and adding it to your existing code. The exact method can vary depending on the specific functionality you want to achieve. However, in general, you would use the ‘addLayer’ function, passing in the layer object as an argument.

    What is the difference between JavaScript layers and HTML layers?

    While both JavaScript and HTML can be used to create layers on a web page, they do so in different ways. HTML layers are created using the ‘div’ tag and are primarily used for layout and design purposes. On the other hand, JavaScript layers are more dynamic and can be used to add interactivity and complex functionality to a web page.

    Can I use JavaScript layers with Google Maps?

    Yes, JavaScript layers can be used with the Google Maps API to add additional functionality to your maps. For example, you can use JavaScript layers to add markers, polygons, and overlays to a map, or to handle user interactions.

    How do I remove a layer in JavaScript?

    Removing a layer in JavaScript can be done using the ‘removeLayer’ function. You would pass in the layer object that you want to remove as an argument to this function.

    What are some common uses of JavaScript layers?

    JavaScript layers are commonly used to add interactivity to web pages. This can include things like pop-up menus, image sliders, form validation, and more. They can also be used to add additional functionality to APIs, like Google Maps.

    How do JavaScript layers affect website performance?

    If used correctly, JavaScript layers can enhance website performance by making pages more responsive and interactive. However, if too many layers are used, or if they are not managed properly, they can slow down a website and negatively impact user experience.

    Can I use JavaScript layers with other programming languages?

    Yes, JavaScript layers can be used in conjunction with other programming languages. For example, you might use PHP or Python to handle server-side operations, while using JavaScript layers to handle client-side interactivity.

    Are there any best practices for using JavaScript layers?

    Some best practices for using JavaScript layers include keeping your layers organized and clearly separated, using comments to explain what each layer does, and testing your layers thoroughly to ensure they work correctly across different browsers and devices.

    Where can I learn more about JavaScript layers?

    There are many resources available online for learning about JavaScript layers. Websites like Mozilla Developer Network (MDN), Google Developers, and SitePoint offer comprehensive guides and tutorials. Additionally, online coding bootcamps and courses on platforms like Coursera and Udemy can also be helpful.