Skip to content

It ends…

Well, after a little over 8 months I’ve finished the book. Technically there’s still a ~300 page index, but I don’t think there’d be much value in leisurely reading that. Now that the experiment is over, I have mixed feelings about writing up reviews/notes on each chapter. For the first 10 chapters I thought it was a great exercise, but as I progressed further, it became somewhat of a pain go back and write up notes on the chapter – though I still felt there was value in doing it.

Blogging about chapters got me thinking about the information more, which is certainly valuable. This wont be one of those books where in 6 months time I go “What did I just read?”, so maybe I will try this again. Anyway, if you by chance come across this blog looking for information on “JavaScript: The Definitive Guide”, I can say it’s worth picking up and has a lot of great information.

Chapter 22: HTML5 APIs

This entry is simply notes for “Chapter 22: Chapter 22: HTML5 APIs” from “JavaScript: The Definitive Guide”

Without a doubt, this was probably my favorite chapter. It covers a slew of new HTML5 technologies that didn’t really fit anywhere else in the book. I’d read about many of them before, but it was nice to get a more in-depth discussion, and it wasn’t until now that I realized how cool Web Workers and IndexedDB really are. Now I just need to think up a project where I can use them.

  • Geolocation API – Allows you to get information about where a user is. Users must give your site permission to use this API. The API is available through navigator.geolocation.
  • History Management – The new pushState/popState/replaceState methods of the history API allow you to create single page web apps without breaking the web. This is how single page web apps should update their URLs. URLs can currently be updated by updating a URL’s hash, but this isn’t friendly to search bots, and the hash is never sent back to the server, so it can create other headaches.
  • Cross-Origin Messaging – The postMessage function allows you to send messages to other windows. You can control which windows can see the message by adjusting the origin parameter. You can also listen to messages from other windows by listening for the “message” event.
  • Web Workers – Allow for threads in JavaScript. A worker exists in its own execution environment and can communicate with the main JavaScript execution environment via message messaging. Workers cannot modify the DOM. Workers can load scripts via the importScripts function. Debugging workers can be a pain as they cannot directly print to the console.
  • Typed Arrays – Created to allow JavaScript programs to more quickly work with binary data.
  • Blobs – Stands for “Binary Large OBject”. You can only preform a limited number of operations on Blobs, so you’ll need to use a more refined Interface if you want to preform special operations.
  • Blob URLs – Allow you to create links to blobs so that they can be referenced by the src property of HTML elements. Blob URLs follow the SOP and have the origin of the script that created them. They are not permanent and disappear when the user navigates away from the document that created them.
  • Filesystem API – Allows web pages to create a local filesystem where they can create files and directories. Experimental at the moment. I’m not sure why someone would use this over IndexedDB or other types of local storage though.
  • Web SQL Database – This would have allowed developers to create client-side relational databases which they could query using SQL. Sadly work on this stopped in 2010 and it will most likely not become a W3C recommendation.
  • IndexedDB – An object database, scoped to a document’s origin. Operations happen in the context of transactions. Indexes can be created for certain fields which make querying the database faster.
  • Websockets – Allows JavaScript programs to create bi-directional socket-type connections to servers.

Chapter 21: Scripted Media and Graphics

This entry is simply notes for “Chapter 21: Scripted Media and Graphics” from “JavaScript: The Definitive Guide”

This chapter aimed to show how to script images, audio, and video using JavaScript. It starts off with a neat technique for scripting image roll overs and then goes into how to manipulate the new Audio and Video HTML elements. The bulk of the chapter, however, is dedicated to image manipulation with SVG graphics and the canvas element (though mainly the canvas element).

SVG is an XML grammar for creating graphics. Unlike raster formats which are matrices of pixels, SVG is a resolution independent vector format where you specify the steps to create an image. It’s interesting because you can embed an SVG element on your page, and then manipulate its contents using the DOM API. It’s recommended that you dynamically create an SVG element using the document.createElementNS method. This method is used so the SVG element will work in browsers that don’t support the HTML5 API. However, SVG is not supported in IE8 and lower, so even with this method your audience is pretty limited.

Whole books have been written on the canvas element, so summing it up with a hand full of notes would be pretty hard. I was already pretty familiar with the element, but the chapter gave it a good treatment. Canvas appears to be what you want to use when creating graphics. SVG is more appropriate if you don’t want to manage redrawing and have sub-elements you want to manipulate with the DOM API.

One interesting side note is that the chapter does not cover the new Web Audio API or the previous audio API that FireFox was working on. I suppose these are too new to really be covered in a book yet (in fact, the FireFox one seems to now be deprecated).

Chapter 20: Client-Side Storage

This entry is simply notes for “Chapter 20: Client-Side Storage” from “JavaScript: The Definitive Guide”

This chapter discusses 4 client-side storage techniques. They are:

  • localStorage and sessionStorage – Two new client-side objects for storing a reasonable amount of data (5MB-10MB depending on the browser). sessionStorage is scoped to the window and origin, and is cleared when the window closes. localStorage is scoped to the origin and is permanent.
  • Cookies – Cookies have been around forever. They’re intended for storing small amounts of data and they’re aren’t terribly secure. Additionally, the API for working with them sucks.
  • IE userData Persistence – A strange localStorage-type object that been available since IE5. It’s only worth knowing about if you’re going to create an IE polyfill for IE versions before IE8.
  • Application Storage and Offline Webapps – Very cool, a way for creating offline web applications.

Chapter 19: The jQuery Library

This entry is a review of “Chapter 19: The jQuery Library” from “JavaScript: The Definitive Guide”

This was a great chapter and provided an excellent overview/introduction to jQuery. I’ve used jQuery quiet a bit in the past, but I’d never really taken the time to drive in and read about all the major areas. This chapter discusses animation, ajax, event handing, plugins, the global utility functions, the major jQuery methods, DOM manipulation, and the basics of the querying. It’s almost like it’s own little sub-book within the book. The only part of the chapter that wasn’t very clear was the section on jQuery queues, but that was just a minor piece.

In a book that’s focused mostly on the JavaScript core and client-side browser APIs, it’s interesting that jQuery gets it’s own chapter and that the other major JavaScript libraries are left out. I’m assuming this is because jQuery powers so much of the web, and anyone doing JavaScript should probably be taking advantage of a JS library (so at least one should be covered). It might have been nice to give the basics of the other major libraries, but then again that may not have been practical, and it’s probably better to cover one library well, than just give glimpses into a hand full. Anyway, overall an good read and a great overview of jQuery.

Chapter 18: Scripted HTTP

This entry is a review of “Chapter 18: Scripted HTTP” from “JavaScript: The Definitive Guide”

This chapter discusses how scripted HTTP can be preformed in JavaScript. Below are my notes.

  • Comet – Refers to a web architecture where the server asynchronously pushes updates to the client (Ajax is the reverse of this – the client asynchronously sends data to the server).
  • The XMLHttpResponse object allows for these methods: GET, POST, DELETE, HEAD, OPTIONS, and PUT.
  • XMLHttpRequest object automatically handles cookies, connection lifetime (though you can abort), *charset*, encoding negotiations, and the “Content-Length”, “Date”, “Referer”, and “User-Agent” headers.
  • The XMLHttpRequest API is designed as if each method was writing to a network stream. Thus, you cannot set request headers before you call open. (the order of operations matter)
  • The status code, response headers and response text are available upon a completed response from the XMLHttpRequest object.
  • overrideMimeType – Method of XMLHttpRequest object that allows you to override the mime type returned by the server.
  • XHR2 – New XMLHttpRequest specification that provides numerous improvements (CORS, file uploads, etc etc).
  • Forms with key/value pairs and files, must be submitted using the “multipart/form-data” mime type. This kind of object can be constructed using a FormData object.
  • For XHR2, you can monitor the progress of downloads/uploads with the progress API.
  • JSONP allows for cross-origin communication, but has security risks.
  • EventSource – This object can be used to implement Comet. In recent months its taken a backseat to WebSockets (which allow two-way communication and have their own protocol). However, Server Side Events happen over HTTP, are one way, and can generate custom events, so they have their place.

Chapter 17: Handling Events

This entry is a review of “Chapter 17: Handling Events” from “JavaScript: The Definitive Guide”

This chapter discusses how web page events are handled with JavaScript. Below are my notes.

  • focusin and focusout have been standardized as bubbling alternatives to the focus and blur events.
  • mouseenter and mouseleave have been standardized as non-bubbling alternatives to the mouseover and mouseout events.
  • The keypress event has been deprecated (what???) in favor of a textinput event.
  • Lots of new HTML5 APIs introduced (drag and drop API, video, sound, mobile events, etc etc).
  • Event Handler Attributes are events set in the HTML (ex: onclick=”alert(‘hi’);”).
  • When you specify an Event Handler Attribute in your HTML, its converted to a function that looks like this: (it will also be defined in non-strict mode)
    function(event) {
      with(document) {
        with(this.form || {}) {
          with(this) {
            /* your code here */
          }
        }
      }
    }
    
  • addEventListener – Functions are invoked for an event in the order they were registered. Calling addEventListener twice on the same object with the same parameters does nothing (a function will not be added twice nor will the function call order be changed).
  • attachEvent is different than addEventListener in the following ways: 1) It only supports event bubbling. 2) The event name is expected to be prefixed with “on”. 3) The same event handler function can be registered multiple times for an event on an object. 4) The “this” keyword inside of handlers will be the window object instead of the element the event was invoked on.
  • In IE8 and before, event handlers registered by setting a property (ex: elm.onclick = …) are not passed an event object. Instead, the event object is made available through window.event. attachEvent handlers, are passed an event object. To mitigate this mess, you can say “elm = evt || window.event” (if evt is passed to the function) in your event handlers.
  • Event handlers registered as properties (elm.onclick = …) can return false to prevent the default action.
  • To cancel the default action of event added via addEventListener, invoke the preventDefault() method of the event object. For handlers register with attachEvent, set the returnValue property of the event object to false (ex: evt.preventDefault(); evt.returnValue = false;)
  • To stop the propagation of an event, invoke the stopPropagation method of the event object. For IE, set the cancelBubble property of the event object to true.
  • onbeforeunload – Return a string from this event and a yes/no prompt will pop up for the user when they try to leave the page.
  • stopImmediatePropagation – “If several listeners are attached to the same element for the same event type, they are called in order in which they have been added. If during one such call, event.stopImmediatePropagation() is called, no remaining listeners will be called.”
  • All modern browsers support mousewheel properties, but they’re not insync, so code must be written to make things work in a cross browser fashion.

Chapter 16: Scripting CSS

This entry is a review of “Chapter 16: Scripting CSS” from “JavaScript: The Definitive Guide”

This chapter discusses the how to manipulate the style of web pages using JavaScript. The first half of the chapter is basically and introduction to CSS, while the second half focuses on working with CSS in JavaScript. I’ve done a lot with CSS already, but there were still a few interesting tid bits that caught my eye. Below are my notes.

  • CSS3 introduces the box-sizing property, which when set to border-box, lets you use IE’s old CSS box model. The default value of box-sizing is content-box.
  • The style property of an element is a CSSStyleDeclaration object. It allows you to get and set the inline styles of a particular object. Since you’re working with inline style and not computed style, it’s best to use in a write-only fashion.
  • When using the style property in JavaScript, properties that are reserved words (like float) are prefixed with “css” (ex: elm.style.cssFloat).
  • The style property has a cssText attribute which allows you to set and get raw CSS.
  • Use window.getComputedStyle(elm, pseudo-class), to get the computed style of an element. Results are read-only and returned in absolute units (ie, no percentages, just pixels). IE8 and below use a currentStyle property which returns relative units.
  • document.styleSheets is an array of all of the style sheets in a document. Each style sheet has a disabled property, which allows you to enable/disable the style sheet.
  • Members of the document.styleSheets array have a “cssRules” property (“rules” in IE8 and before), which allow you to loop through individual rules. Each rule has a selectorText property (which represents the selector) and a style property (which is a CSSStyleDeclaration object). Rules can be inserted and removed, but the API differs between IE8 and before, and other browsers.
  • Chapter 15: Scripting Documents

    This entry is a review of “Chapter 15: Scripting Documents” from “JavaScript: The Definitive Guide”

    This chapter discusses the how to manipulate the underlying structure of a web page using JavaScript. Every window has a document object which represents the displayed webpage. The API for manipulating and working with the document object is known as the DOM (Document Object Model). I was already pretty familiar with most of API functions discussed, but this chapter definitely helped fill in the gaps. Below are my notes.

    • getElementsByName – What’s interesting about this document method is that in IE, it’ll also return elements with an ID attribute equal to what you put in. Another point to make is that the name attribute is only valid for certain elements and that variables pointing to these elements get created under the window and document objects.
    • NodeList and HTMLCollection are two document collection types returned when referencing values like document.forms or methods like document.getElementsByTagName. Which is returned appears to be browser dependent.
    • getElementsByClassName – document method introduced in FF3 and IE9. IE8 can use querySelectorAll to emulate this call.
    • querySelectorAll – document method introduced in FF3 and IE8. Allows you to get elements via the CSS selector syntax.
    • document.all – An old way of selecting multiple elements (ex: document.all.tags(“div”)).
    • Document Traversal – You can traverse a document by nodes (which will include text nodes) or by element (which will only include HTML elements). parentNode is always an Element since text nodes and comment nodes can’t have childen. The other traversal properties are pretty self explanatory – childNodes vs children, nextSibling vs nextElementSibling, etc etc.
    • html and css prefixes – For HTML elements with attributes that are reserved words (such as “for” on a label element), prefix it with html -> “htmlFor” when working with the HTML element (the one exception being class, which is className). For CSS properties under the style property, prefix reserved names with “css”.
    • getAttribute, setAttribute – Useful for working with and creating non-standard element attributes.
    • hasAttribute, removeAttribute – Useful for detecting and removing attributes (especially ones defined by presence, like selected).
    • dataset – Elements will have a dataset property which refers to non-standard properties prefixed with “data-“. This API allows you to add non-standard properties and still have “valid” HTML.
    • attributes – NodeList comprising an element’s attributes. Useful for possibly looping through the attributes.
    • insertAdjacentHTML – Allows you to insert HTML into an existing code without overriding its content.
    • textContent – Allows you to get or set the text of an element/node (IE uses innerText in place of this).
    • Script text – Browsers ignore the content of script tags if they do not recognize their type attribute.
    • cloneNode – A method of a node, returned a cloned version of itself (takes in a boolean value which indicates if descendents should be copied).
    • replaceChild – Replaces one node with another.
    • DocumentFragment – Allows you to manipulate, create, and append multiple nodes at once. Good for performance reasons in certain cases.
    • getBoundingClientRect – Returns an elements position in viewport cordinates. To get document coordinates, use the offsetLeft/offsetTop/offsetParent properties of an element.
    • getClientRects – Useful for getting the rects the enclose an inline multiline element.
    • scrollIntoView – Scrolls an element into view.
    • elementFromPoint – Given x,y viewport coordinates, you get the upper most element at that point.
    • scrollTop and scrollLeft are read write, therefore, you never really need to call scrollTo().
    • placeholder – An attribute for textboxes. It’s a string that appears when there is no text.
    • clientWidth and clientHeight are like offsetWidth and offsetHeight except that they do not include the border size, only the content area and its padding. Also, if the browser has added scrollbars between the padding and the border, clientWidth and clientHeight do not include the scrollbar in their returned value.
    • document.documentElement – Represents the root of the document. For HTML documents, it represents the HTML tag.
    • document.referrer – Returns the referrer of a web page.
    • window.getSelection – Returns the selection object for a webpage (indicating text that is selected). IE uses a different API.
    • contenteditable – Allows for elements to be editable by the user. See execCommand for info on edit commands.

    Chapter 14: The Window Object

    This entry is a review of “Chapter 14: The Window Object” from “JavaScript: The Definitive Guide”

    This chapter discusses the global object of client-side JavaScript, the window object. Sometimes referred to as the BOM (Browser Object Modal), the window object contains a number of client-side specific objects, some of which are not related to the window (ex: setTimeout). Overall I enjoyed this chapter. Below are my notes.

    • The location property of window refers to the Browser’s Location object. Interestingly, the document’s location property points to the exact same object (window.location === document.location). The toString method of Location resolves to its href property, and attempting to set the location object causes the browser to navigate to the given URL.
    • The history property of window lets you move forward or backward in a page’s history, but does not give you access to content/location data of the history. Due to complexity issues, HTML5 libraries should be used for managing state.
    • The navigator property of window contains information about the web browser. Due to competing browsers trying to stay reliant, many of the fields are meaningless. The userAgent field is typically used for browser sniffing, but this is a complex process. There are some other interesting fields like onLine (tells you if you’re connected to a network), geolocation (gives you geolocation), javaEnabled(), and cookiesEnabled().
    • The screen property of window refers to the Screen object which gives you information about the size and color depth of the user’s monitor.
    • showModalDialog – Allows you to create a custom popup. Setting window.returnValue inside of the popup serves as the value that’s returned to the main window when the popup is closed. Pop-ups have access to passed parameters via window.dialogArguments.
    • window.onerror – The last stop before an error is presented to the user. Function handlers for this take in 3 arguments instead of an exception object. If it returns false, the error was handled – except in FireFox, where returning true means the error was handled.
    • Opening popups – Windows only have access to popups they create. Popups have access to their creator via the opener property. Popups can also only happen in response to a user event, and not regular events like the page load event.
    • The ids of document elements become non-enumerable global variables. If a variable is created, it overshadows this implicit declaration.
    • window.frames[] = window[] (in HTML5).
    • f.contentWindow refers to window element of iframe f (where f is an element).
    • Each frame in a page has its own JavaScript context. This screws up operators like instanceof.
    • The window object isn’t really the global object, it’s a proxy for the global object known as the windowproxy object. This is because frames and windows can reload data, and you don’t want to erase the resource that’s pointing that space.