# data[].attributes.body
Kraken or
https://browserbench.org/JetStream/ or Octane 2.0 below

# data[].attributes.attachment_link.readable_text
When a browser reads a style sheet, it will format the HTML document according to the information in the style sheet.

Three Ways to Insert CSS

There are three ways of inserting a style sheet:

External CSS

With an external style sheet, you can change the look of an entire website by changing just one file!

Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.

Example

External styles are defined within the <link> element, inside the <head> section of an HTML page:

Try it Yourself "

An external style sheet can be written in any text editor, and must be saved with a .css extension.

The external .css file should not contain any HTML tags.

Here is how the "mystyle.css" file looks:

"mystyle.css"

body {
background-color: lightblue;
}

Note: Do not add a space between the property value (20) and the unit (px):
Incorrect (space): margin-left: 20 px;
Correct (no space): margin-left: 20px;

Internal CSS

An internal style sheet may be used if one single HTML page has a unique style.

The internal style is defined inside the <style> element, inside the head section.

Example

Internal styles are defined within the <style> element, inside the <head> section of an HTML page:

Try it Yourself "

Inline CSS

An inline style may be used to apply a unique style for a single element.

To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.

Example

Inline styles are defined within the "style" attribute of the relevant element:

Try it Yourself "

Tip: An inline style loses many of the advantages of a style sheet (by mixing content with presentation). Use this method sparingly.

Multiple Style Sheets

If some properties have been defined for the same selector (element) in different style sheets, the value from the last read style sheet will be used.

Assume that an external style sheet has the following style for the <h1> element:

Then, assume that an internal style sheet also has the following style for the <h1> element:

Example

If the internal style is defined after the link to the external style sheet, the <h1> elements will be "orange":

Try it Yourself "

Example

However, if the internal style is defined before the link to the external style sheet, the <h1> elements will be "navy":

Try it Yourself "

Cascading Order

What style will be used when there is more than one style specified for an HTML element?

All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules, where number one has the highest priority:

1. Inline style (inside an HTML element)

2. External and internal style sheets (in the head section)

3. Browser default

So, an inline style has the highest priority, and will override external and internal styles and browser defaults.
Try it Yourself "
Ever heard about W3Schools Spaces? Here you can create your own website, or save code snippets for later use, for free.

Get started for free ❯
* no credit card required

# data[].attributes.attachment_link.description
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

# data[].attributes.body
Try running this (Octane) in several browsers several times. It measures the speed of the JavaScript engine. Different browsers have different JS engines, so they will run the JavaScript at different speeds.

# data[].attributes.attachment_link.description
Octane 2.0 JavaScript Benchmark - the Javascript benchmark for the modern web

# data[].attributes.attachment_link.title
How does JavaScript handle AJAX responses in the background?

# data[].attributes.attachment_link.description
Since JavaScript runs in a single thread, after an AJAX request is made, what actually happens in the background? I would like to get a deeper insight into this, can anyone shed some light?

# data[].attributes.body
Often 3rd party software used - may be vulnerable. eg. Gov text to speech widget.

Because compiled at client side, firewall may not detect risk

Cross domain data leakage. Javascript can call for info from another domain. New to HTML5

# data[].attributes.body
Browser specific code looks like it could be necessary (or a solution), but this is a problem - browser detection not perfect. Instead, use libraries.

# data[].attributes.body
CSS class id pseudo-classes
CSS Selectors

# data[].attributes.body
JavaScript explained
JavaScript Introduction
JavaScript Beginners

# data[].attributes.body
Box model explained

# data[].attributes.headline
JavaScript sinks are properties, functions and other client-side entities that that can lead to or influence client-side code execution. Here are some common exploitable JavaScript sinks:Execution-based, such as eval(), Function(), setTimeout(), setInterval() and so on.URL-based, for instance location and location.assign().HTML-based, such as document.write(), HTML elements and attributes.XHR calls, postMessage, client-side storage and other JavaScript variables.

# data[].attributes.subject
JavaScript sinks are properties, functions and other client-side entities that that can lead to or influence client-side code execution. Here are some common exploitable JavaScript sinks:Execution-based, such as eval(), Function(), setTimeout(), setInterval() and so on.URL-based, for instance location and location.assign().HTML-based, such as document.write(), HTML elements and attributes.XHR calls, postMessage, client-side storage and other JavaScript variables.

# data[].attributes.attachment_link.readable_text
When the words 'Java' and 'security' are used together, a common assumption is that the reference is to server-side Java. Myths abound here, such as the belief that security is a server-side concern and that JavaScript itself cannot have security issues [see box: JavaScript myth busting]. However, in recent times, with the popularity of Web 2.0, Ajax and rich Internet applications, JavaScript and its attendant vulnerabilities have become highly prevalent in Indian organizations.

JavaScript myth busting

The perceptions that critical operations are performed on the server side and that all data is stored there are incorrect. What many browsers do today involves reaching out over an unencrypted connection to an unverified site, grabbing code and executing it.

Client-side storage is gaining prominence with HTML5. Client-side logic is also on the rise, as this is an opportunity for developers to offload processing to the user, saving bandwidth and machine-time. In reality, all server-side data and functionality can be accessed from the browser using JavaScript.

Securing client-side JavaScript is a problem that has started receiving attention. Third-party JavaScript issues from widgets, embedded code and JavaScript libraries are some of the vulnerable aspects of JavaScript that see active exploitation. This article looks at vulnerabilities in JavaScript and possible best practices for secure JavaScript coding.

JavaScript security issues can be divided into three broad categories:

1) DOM-based cross-site scripting (XSS)

Most security professionals are familiar with cross-site scripting (XSS). While XSS is usually the result of insecurely written server-side code, DOM-based XSS is a kind of XSS occurring entirely on the client-side. With server-side XSS vulnerabilities getting fixed, a shift in focus towards DOM-based XSS is indicated. DOM-based XSS is more serious than ordinary XSS attacks, since such scripting cannot be filtered through a web-application firewall (WAF).

The script injection in DOM-based XSS happens purely on the client-side. Looking for DOM-based XSS is tricky. JavaScript static analysis requires identifying sources and following them into sinks, while JavaScript runtime analysis requires execution and awareness of when and where sources/sinks are being called for execution.

JavaScript sources are functions or DOM properties that can be influenced by the user. Vulnerable JavaScript sources that can be exploited for a DOM-based attack include the following:

Location-based, such as location, location.href, document.URL and so on.

Client-side storage based. For instance, it could be document.cookies, sessionStorage and localStorage.

Navigation-based, such as navigation.referrer, window.name, history et al.

Cross-domain functions.

JavaScript sinks are properties, functions and other client-side entities that that can lead to or influence client-side code execution. Here are some common exploitable JavaScript sinks:

Execution-based, such as eval(), Function(), setTimeout(), setInterval() and so on.

URL-based, for instance location and location.assign().

HTML-based, such as document.write(), HTML elements and attributes.

XHR calls, postMessage, client-side storage and other JavaScript variables.

DOM-based XSS usually happens when source data is put into a sink without proper validation. Sink functions such as eval(), setTimeout() and setInterval() are dangerous, since they make it possible to execute even text passed through them. The input to these functions is controlled completely on the client-side. Completely eliminating the use of eval() is strongly recommended. If used, no user controlled data must be passed through these functions.

In order to mitigate DOM-based XSS it is a good policy to avoid using sources/sinks whenever possible. When unavoidable, perform rigorous white-list based filtering on sources and perform proper encoding before sending data to a sink.

2) Cross-domain information leakage

JavaScript has cross-domain functionality that allows sites to load multiple objects from various sources (widgets or iframes, among others). Until recently, JavaScript had restrictions on accessing/sending data to other domains. However, HTML5 has increased the level of cross-domain access that JavaScript enjoys with the cross-domain XML request function.

When not implemented properly, the use of this function leads to unintentional data leakage. It is best to use a whitelist-based approach when implementing this function-right down to the sub-domain level. This ensures that anonymous JavaScript cannot be executed through public sub-domains.

postMessage is a JavaScript function under HTML5 that facilitates communication across iframes, i.e. two iframes loaded from separate domains on the same page or between the page and an iframe within it. This communication is entirely client-side. If postMessage restrictions are set loosely, it could result in invalidated malicious data being sent across iframes or a potential data leak scenario making it possible to perform data extraction across sites. The white-list paradigm applies here as well.

Prior to HTML5, cross-domain requests were handled using JSON callbacks. Using callback functions in APIs should only be allowed with discretion in cases where the information in question needs to be shared with any and all external parties. Turn these features off when not needed.

3) Client-side logic and data storage

Initially, JavaScript performance and capabilities were very limited, receiving no significant focus from browser developers for improving performance. As JavaScript engines get faster with iterations of browser release, it is possible to perform substantial processing on the client-side.

This can tempt developers to consign sensitive operations to the client-side. While this is unavoidable in some scenarios, it may also be intended to offload processing to the client-side and save server-time and bandwidth.

With HTML5, client-side storage mechanisms have gone beyond the cookie with newer options such as localStorage, Web SQL and IndexDB. Storage of sensitive data on the client side using these mechanisms fosters a huge security risk, bigger than cookies ever posed. These methods unlike cookies, have a longer life-span and larger storage capacity which tempt developers to use them to store potentially sensitive data. Moreover, JavaScript's weak encryption libraries make it likely that developers would merely encode this information rather than encrypt it.

A real world example is hard-coding the username and password into the JavaScript on the client-side. Implementing logical decision-making on the client-side makes the code available to the user. This can result in the user attempting to influence the outcome, since the whole decision making happens within the browser - an environment that the user has full control over.

Operations involving security controls, sensitive logical decision-making and authentication should be avoided on the client-side. Remember, merely disabling right-click functionality or obfuscating code does not prevent access to JavaScript.

About the author: Lavakumar Kuppan is the author of IronWASP, an advanced Web security testing platform. He has also authored multiple other security tools like 'Shell of the Future', JS-Recon, Imposter and the HTLM5 based distributed computing system-Ravan. As a security researcher, Lavakumar has discovered novel attacks that include a sandbox bypass on Flash Player, WAF bypass technique using HTTP parameter pollution, multiple HTML5 attacks and a CSRF protection bypass technique using CickJacking & HPP. His research and tools are available at the Attack and Defense Labs website.

Why subpostmasters and Post Office are battling it out in High Court

Employers turn to wearable technology to help staff manage work-life balance

Object storage: On-prem, in the cloud and hybrid

Download Current Issue

# data[].attributes.attachment_link.title
Vulnerabilities in JavaScript: Secure coding insights and tips

# data[].attributes.attachment_link.description
When the words 'Java' and 'security' are used together, a common assumption is that the reference is to server-side Java. Myths abound here, such as the belief that security is a server-side concern and that JavaScript itself cannot have security issues [see box: JavaScript myth busting].

# data[].attributes.attachment_link.title
Peacekeeper - free universal browser test for HTML5 from Futuremark

# data[].attributes.attachment_link.description
See which HTML5 browser is the fastest browser with this free browser speed test. Test your PC, smartphone or tablet. Works with any browser on any device.

# data[].attributes.body
HTML intro
html tags
How use CSS
CSS internal external
W3Schools

# data[].attributes.body
These are syntax differences. Language has to be different in different browsers

# data[].attributes.attachment_link.readable_text
Please note that this is an older article that discusses JavaScript issues in Internet Explorer versions 6 & 7, along with Firefox versions 2+ & 3.0.
Although the days of long and tedious code branches to target specific browsers in JavaScript are over, once in a while it's still necessary to do some simple code branching and object detection to ensure that a certain piece of code is working properly on a user's machine.

In this article, I'll outine 7 areas where Internet Explorer and Firefox differ in JavaScript syntax.

1. The CSS "float" property

The basic syntax for accessing a specific css property for any given object is object.style.property, using camel casing to replace a hyphenated property. For example, to access the background-color property of a <div> whose ID is "header", we would use the following syntax:

document.getElementById("header").style.backgroundColor= "#ccc";

But since the word "float" is already reserved for use in JavaScript, we cannot access the "float" property using object.style.float. Here is how we do it in the two browsers:
The IE Syntax:

document.getElementById("header").style.styleFloat = "left";

The Firefox Syntax:

document.getElementById("header").style.cssFloat = "left";

2. The Computed Style of an Element

JavaScript can easily access and modify CSS styles that have been set on objects using the object.style.property syntax outlined above. But the limitation of that syntax is that it can only retrieve styles that have been set inline in the HTML or styles that have been set directly by JavaScript. The style object does not access styles set using an external stylesheet. In order to access an object's "computed style", we use the following code:
The IE Syntax:

var myObject = document.getElementById("header");
var myStyle = myObject.currentStyle.backgroundColor;

The Firefox Syntax:

var myObject = document.getElementById("header");
var myComputedStyle = document.defaultView.getComputedStyle(myObject, null);
var myStyle = myComputedStyle.backgroundColor;

3. Accessing the "class" Attribute of an Element

As is the case with the "float" property, our two major browsers use different syntax to access this attribute via the getAttribute method in JavaScript.
The IE Syntax:

var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("className");

The Firefox Syntax:

var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("class");

This syntax would also apply using the setAttribute method.
See a demo page that demonstrates these two different syntaxes
4. Accessing the "for" Attribute of the <label> Tag

Similar to number 3, we have different syntax to access a <label> tag's "for" attribute in JavaScript.
The IE Syntax:

var myObject = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("htmlFor");

The Firefox Syntax:

var myObject = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("for");

5. Getting the Cursor Position

It would be rare that you would want to find the cursor position of an element, but if for some reason you need to, the syntax is different in IE and Firefox. The code samples here are fairly basic, and normally would be part of a much more complex event handler, but they serve to illustrate the difference. Also, it should be noted that the result in IE will be different than that of Firefox, so this method is buggy. Usually, the difference can be compensated for by getting the "scrolling position" - but that's a subject for another post!
The IE Syntax:

var myCursorPosition = [0, 0];
myCursorPosition[0] = event.clientX;
myCursorPosition[1] = event.clientY;

The Firefox Syntax:

var myCursorPosition = [0, 0];
myCursorPosition[0] = event.pageX;
myCursorPosition[1] = event.pageY;

6. Getting the Size of the Viewport, or Browser Window

Sometimes it's necessary to find out the size of the browser's available window space, usually called the "viewport".
The IE Syntax:

var myBrowserSize = [0, 0];
myBrowserSize[0] = document.documentElement.clientWidth;
myBrowserSize[1] = document.documentElement.clientHeight;

The Firefox Syntax:

var myBrowserSize = [0, 0];
myBrowserSize[0] = window.innerWidth;
myBrowserSize[1] = window.innerHeight;

7. Alpha Transparency

Okay, this is not a JavaScript syntax issue - alpha transparency is set via CSS. But when objects fade in and out via JavaScript, this is done by accessing CSS alpha settings, usually inside of a loop. The CSS code that needs to be altered via JavaScript is as follows:
The IE Syntax:

#myElement {
  filter: alpha(opacity=50);
}

The Firefox Syntax:

#myElement {
  opacity: 0.5;
}

So, to access those values via JavaScript, we would use the style object:
The IE Syntax:

var myObject = document.getElementById("myElement");
myObject.style.filter = "alpha(opacity=80)";

The Firefox Syntax:

var myObject = document.getElementById("myElement");
myObject.style.opacity = "0.5";

Of course, as mentioned, normally the opacity/alpha would be changed in the midst of a loop, to create the animating effect, but this simple example clearly illustrates how it's done.

Are There Other Differences?

These are some of the differences I've personally come across either in development or research, but I'm sure there are others. Leave a comment if you think I've left out an important one, and I'll try to update this list, or else do a "Part 2" post.

# data[].attributes.attachment_link.title
7 JavaScript Differences Between Firefox & IE

# data[].attributes.attachment_link.description
Please note that this is an older article that discusses JavaScript issues in Internet Explorer versions 6 & 7, along with Firefox versions 2+ & 3.0. Although the days of long and tedious code branches to target specific browsers in JavaScript are over, once in a while it's still necessary to do some simple code branching and object detection to ensure that a certain piece of code is working properly on a user's machine.

# data[].attributes.body
The problem isn't that there are different versions of JS, but that different browsers implement it differently

# data[].attributes.attachment_link.title
Why do we need different JS for different browsers

# data[].attributes.attachment_link.description
What exactly are different things we need to take care when writing different JS files, like arrays, variables etc., Is there a book or website explaining differences between different JS engines u...

# data[].attributes.attachment_link.readable_text
Introducing CSS Selectors

A CSS selector is the part of a CSS rule set that actually selects the content you want to style. Let's look at all the different kinds of selectors available, with a brief description of each.

Universal Selector

The universal selector works like a wild card character, selecting all elements on a page. Every HTML page is built on content placed within HTML tags. Each set of tags represents an element on the page. Look at the following CSS example, which uses the universal selector:

* {    color: green;    font-size: 20px;    line-height: 25px; }

The three lines of code inside the curly braces ( color, font-size, and line-height) will apply to all elements on the HTML page. As seen here, the universal selector is declared using an asterisk. You can also use the universal selector in combination with other selectors.

Element Type Selector

Also referred to simply as a "type selector," this selector must match one or more HTML elements of the same name. Thus, a selector of nav would match all HTML nav elements, and a selector of <ul> would match all HTML unordered lists, or <ul> elements.

The following example uses an element type selector to match all <ul> elements:

ul {    list-style: none;    border: solid 1px #ccc; }

To put this in some context, here's a section of HTML to which we'll apply the above CSS:

<ul> <li>Fish</li> <li>Apples</li> <li>Cheese</li> </ul> <div class="example"> <p>Example paragraph text.</p> </div> <ul> <li>Water</li> <li>Juice</li> <li>Maple Syrup</li> </ul>

There are three main elements making up this part of the page: Two <ul> elements and a <div>. The CSS will apply only to the two <ul> elements, and not to the <div>. Were we to change the element type selector to use <div> instead of <ul>, then the styles would apply to the <div> and not to the two <ul> elements.

Also note that the styles will not apply to the elements inside the <ul> or <div> elements. That being said, some of the styles may be inherited by those inner elements.

ID Selector

An ID selector is declared using a hash, or pound symbol (#) preceding a string of characters. The string of characters is defined by the developer. This selector matches any HTML element that has an ID attribute with the same value as that of the selector, but minus the hash symbol.

Here's an example:

#container {    width: 960px;    margin: 0 auto; }

This CSS uses an ID selector to match an HTML element such as:

In this case, the fact that this is a <div> element doesn't matter-it could be any kind of HTML element. As long as it has an ID attribute with a value of container, the styles will apply.

An ID element on a web page should be unique. That is, there should only be a single element on any given page with an ID of container. This makes the ID selector quite inflexible, because the styles used in the ID selector rule set can be used only once per page.

If there happens to be more than one element on the page with the same ID, the styles will still apply, but the HTML on such a page would be invalid from a technical standpoint, so you'll want to avoid doing this.

In addition to the problems of inflexibility, ID selectors also have the problem of very high specificity.

Class Selector

The class selector is the most useful of all CSS selectors. It's declared with a dot preceding a string of one or more characters. Just as is the case with an ID selector, this string of characters is defined by the developer. The class selector also matches all elements on the page that have their class attribute set to the same value as the class, minus the dot.

Take the following rule set:

.box {    padding: 20px;    margin: 10px;    width: 240px; }

These styles will apply to the following HTML element:

The same styles will also apply to any other HTML elements that have a class attribute with a value of box. Having multiple elements on a single page with the same class attribute is beneficial, because it allows you to reuse styles, and avoid needless repetition. In addition to this, class selectors have very low specificity-again, more on this later.

Another reason the class selector is a valuable ally is that HTML allows multiple classes to be added to a single element. This is done by separating the classes in the HTML class attribute using spaces. Here's an example:

Descendant Combinator

The descendant selector or, more accurately, the descendant combinator lets you combine two or more selectors so you can be more specific in your selection method. For example:

#container .box {    float: left;    padding-bottom: 15px; }

This declaration block will apply to all elements that have a class of box that are inside an element with an ID of container. It's worth noting that the .box element doesn't have to be an immediate child: there could be another element wrapping .box, and the styles would still apply.

Look at the following HTML:

If we apply the CSS in the previous example to this section of HTML, the only element that'll be affected by those styles is the first <div> element that has a class of box. The <div> element that has a class of box-2 won't be affected by the styles. Similarly, the second <div> element with a class of box won't be affected because it's not inside an element with an ID of container.

You should be careful when using the descendant combinator in your CSS. This kind of selector, while making your CSS a little easier to read, can unnecessarily restrict your styles to a specific context-in this case, the styles are restricted to boxes inside of #container -which can make your code inflexible.

Child Combinator

A selector that uses the child combinator is similar to a selector that uses a descendant combinator, except it only targets immediate child elements:

#container > .box {    float: left;    padding-bottom: 15px; }

This is the same code from the descendant combinator example, but instead of a space character, we're using the greater-than symbol (or right angle bracket.)

In this example, the selector will match all elements that have a class of box and that are immediate children of the #container element. That means, unlike the descendant combinator, there can't be another element wrapping .box -it has to be a direct child element.

Here's an HTML example:

In this example, the CSS from the previous code example will apply only to the first <div> element that has a class of box. As you can see, the second <div> element with a class of box is inside another <div> element. As a result, the styles will not apply to that element, even though it too has a class of box.

Again, selectors that use this combinator can be somewhat restricting, but they can come in handy-for example, when styling nested lists.

General Sibling Combinator

A selector that uses a general sibling combinator matches elements based on sibling relationships. That is to say, the selected elements are beside each other in the HTML.

h2 ~ p {    margin-bottom: 20px; }

This type of selector is declared using the tilde character (~). In this example, all paragraph elements (<p>) will be styled with the specified rules, but only if they are siblings of <h2> elements. There could be other elements in between the <h2> and <p>, and the styles would still apply.

Let's apply the CSS from above to the following HTML:

<h2>Title</h2> <p>Paragraph example.</p> <p>Paragraph example.</p> <p>Paragraph example.</p> <div class="box"> <p>Paragraph example.</p> </div>

In this example, the styles will apply only to the first three paragraph elements. The last paragraph element is not a sibling of the <h2> element because it sits inside the <div> element.

Adjacent Sibling Combinator

A selector that uses the adjacent sibling combinator uses the plus symbol (+), and is almost the same as the general sibling selector. The difference is that the targeted element must be an immediate sibling, not just a general sibling. Let's see what the CSS code for this looks like:

p + p {    text-indent: 1.5em;    margin-bottom: 0; }

This example will apply the specified styles only to paragraph elements that immediately follow other paragraph elements. This means the first paragraph element on a page would not receive these styles. Also, if another element appeared between two paragraphs, the second paragraph of the two wouldn't have the styles applied.

So, if we apply this selector to the following HTML:

<h2>Title</h2> <p>Paragraph example.</p> <p>Paragraph example.</p> <p>Paragraph example.</p> <div class="box"> <p>Paragraph example.</p> <p>Paragraph example.</p> </div>

...the styles will apply only to the second, third, and fifth paragraphs in this section of HTML.

Attribute Selector

The attribute selector targets elements based on the presence and/or value of HTML attributes, and is declared using square brackets:

input[type="text"] {    background-color: #444;    width: 200px; }

There should not be a space before the opening square bracket unless you intend to use it along with a descendant combinator. The above CSS would match the following element:

But it wouldn't match this one:

The attribute selector can also be declared using just the attribute itself, with no value, like this:

input[type] {    background-color: #444;    width: 200px; }

This will match all input elements with an attribute of type, regardless of the value.

You can also use attribute selectors without specifying anything outside the square brackets (thus targeting based on the attribute alone, irrespective of the element). It's also worth noting that, when using values, you have the option to include quotes (single or double,) or not.

Pseudo-class

A pseudo-class uses a colon character to identify a pseudo-state that an element might be in-for example, the state of being hovered, or the state of being activated. Let's look at a common example:

a:hover {    color: red; }

In this case, the pseudo-class portion of the selector is the :hover part. Here we've attached this pseudo-class to all anchor elements ( elements). This means that when the user hovers their mouse over an element, the color property for that element will change to red. This type of pseudo-class is a dynamic pseudo-class, because it occurs only in response to user interaction-in this case, the mouse moving over the targeted element.

It's important to recognize that these types of selectors do not just select elements; they select elements that are in a particular state. For the purposes of this example, the state is the "hover" state.

Pseudo-element

Finally, CSS has a selector referred to as a pseudo-element and, used appropriately, it can be very useful. The only caveat is that this selector is quite different from the other examples we've considered. Let's see a pseudo-element in context:

.container:before {    content: "";    display: block;    width: 50px;    height: 50px;    background-color: #141414; }

This example uses one kind of pseudo-element, the :before pseudo-element. As the name suggests, this selector inserts an imaginary element into the page, inside the targeted element, before its contents.

# data[].attributes.attachment_link.description
A CSS selector is the part of a CSS rule set that actually selects the content you want to style. Let's look at all the different kinds of selectors available, with a brief description of each. The universal selector works like a wild card character, selecting all elements on a page.

# data[].attributes.body
Chapter 1 is helpful

# data[].attributes.attachment_link.description
Chapter 3. The Nature of JavaScript Table of contents Buy the book

# data[].attributes.attachment_link.readable_text
What Is JavaScript?

JavaScript is a high-level, interpreted programming language that has been widely used since its release in 1995. JavaScript is currently the world's 11th most popular programming language. JavaScript is commonly used in dynamic web pages to provide extended functionalities such as form submission/validation, interactivity, animations, user activity tracking and more. In order to do this, a JavaScript function is embedded in an HTML page, where it can interact with that page's Document Object Model (DOM) to perform specific functions. JavaScript is not to be confused with the Java programming language - the languages are both object-oriented, have C-like syntaxes and share several names and naming conventions, but are otherwise not related. In addition to its use in web browser applications, Javascript is increasingly used in mobile applications, via cross-platform development tools like Titanium and PhoneGap, and in server-side code via frameworks like Node.js.

JavaScript Security

Since its release, there have been several JavaScript security issues that have gained widespread attention. For one, the way JavaScript interacts with the DOM poses a risk for end users by enabling malicious actors to deliver scripts over the web and run them on client computers. There are two measures that can be taken to contain this JavaScript security risk. First is sandboxing, or running scripts separately so that they can only access certain resources and perform specific tasks. The second measure is implementing the same origin policy, which prevents scripts from one site from accessing data that is used by scripts from other sites. Many JavaScript security vulnerabilities are the result of browser authors failing to take these measures to contain DOM-based JavaScript security risks.

Common JavaScript Security Vulnerabilities

One of the most common JavaScript security vulnerabilities is Cross-Site Scripting (XSS). Cross-Site Scripting vulnerabilities enable attackers to manipulate websites to return malicious scripts to visitors. These malicious scripts then execute on the client side in a manner determined by the attacker. XSS vulnerabilities can exist when browser or application authors fail to implement the same origin policy and can be prevented by following correct development techniques. If XSS vulnerabilities aren't remediated, they can result in user data theft, account tampering, malware spreading or remote control over a user's browser.

Another common JavaScript security vulnerability is Cross-Site Request Forgery (CSRF). Cross-Site Request Forgery vulnerabilities allow attackers to manipulate victims' browsers to take unintended actions on other sites. This is possible when target sites authenticate requests solely using cookies and attackers are able to send requests carrying users' cookies. This JavaScript security issue can lead to account tampering, data theft, fraud and more. Both Cross-Site Scripting and Cross-Site Request Forgery vulnerabilities exist in the application layer and require that correct development techniques are followed in order to be avoided.

There are a variety of other common JavaScript security issues that can increase risks for users. These issues include improper client-server trust relationships, vulnerabilities in browser and browser plugin code, and incorrect implementation of sandboxing or same origin policy. And for Node.js-based server side applications, there may be many other security vulnerabilities, including SQL Injection, Command Injection, and others. The only way for organizations to avoid these JavaScript security risks is to develop and source applications that are free of JavaScript security vulnerabilities. Many organizations use JavaScript security analyzers to test for and remediate these vulnerabilities.

JavaScript Security Analyzers

JavaScript security analyzers are JavaScript security tools that perform code analysis on client-side applications. These analyzers can typically test for JavaScript security vulnerabilities, issues in implementation, configuration errors and other risks that can be exploited by attackers. The Veracode platform provides JavaScript security analysis through its automated cloud-based service. Veracode assesses web applications and client-side technologies in a running environment in order to discover JavaScript security vulnerabilities and other issues.

# data[].attributes.attachment_link.description
JavaScript is a high-level, interpreted programming language that has been widely used since its release in 1995. JavaScript is currently the world's 11th most popular programming language. JavaScript is commonly used in dynamic web pages to provide extended functionalities such as form submission/validation, interactivity, animations, user activity tracking and more.

# data[].attributes.attachment_link.readable_text
What Is JavaScript?

JavaScript is a high-level, interpreted programming language that has been widely used since its release in 1995. JavaScript is currently the world's 11th most popular programming language. JavaScript is commonly used in dynamic web pages to provide extended functionalities such as form submission/validation, interactivity, animations, user activity tracking and more. In order to do this, a JavaScript function is embedded in an HTML page, where it can interact with that page's Document Object Model (DOM) to perform specific functions. JavaScript is not to be confused with the Java programming language - the languages are both object-oriented, have C-like syntaxes and share several names and naming conventions, but are otherwise not related. In addition to its use in web browser applications, Javascript is increasingly used in mobile applications, via cross-platform development tools like Titanium and PhoneGap, and in server-side code via frameworks like Node.js.

JavaScript Security

Since its release, there have been several JavaScript security issues that have gained widespread attention. For one, the way JavaScript interacts with the DOM poses a risk for end users by enabling malicious actors to deliver scripts over the web and run them on client computers. There are two measures that can be taken to contain this JavaScript security risk. First is sandboxing, or running scripts separately so that they can only access certain resources and perform specific tasks. The second measure is implementing the same origin policy, which prevents scripts from one site from accessing data that is used by scripts from other sites. Many JavaScript security vulnerabilities are the result of browser authors failing to take these measures to contain DOM-based JavaScript security risks.

Common JavaScript Security Vulnerabilities

One of the most common JavaScript security vulnerabilities is Cross-Site Scripting (XSS). Cross-Site Scripting vulnerabilities enable attackers to manipulate websites to return malicious scripts to visitors. These malicious scripts then execute on the client side in a manner determined by the attacker. XSS vulnerabilities can exist when browser or application authors fail to implement the same origin policy and can be prevented by following correct development techniques. If XSS vulnerabilities aren't remediated, they can result in user data theft, account tampering, malware spreading or remote control over a user's browser.

Another common JavaScript security vulnerability is Cross-Site Request Forgery (CSRF). Cross-Site Request Forgery vulnerabilities allow attackers to manipulate victims' browsers to take unintended actions on other sites. This is possible when target sites authenticate requests solely using cookies and attackers are able to send requests carrying users' cookies. This JavaScript security issue can lead to account tampering, data theft, fraud and more. Both Cross-Site Scripting and Cross-Site Request Forgery vulnerabilities exist in the application layer and require that correct development techniques are followed in order to be avoided.

There are a variety of other common JavaScript security issues that can increase risks for users. These issues include improper client-server trust relationships, vulnerabilities in browser and browser plugin code, and incorrect implementation of sandboxing or same origin policy. And for Node.js-based server side applications, there may be many other security vulnerabilities, including SQL Injection, Command Injection, and others. The only way for organizations to avoid these JavaScript security risks is to develop and source applications that are free of JavaScript security vulnerabilities. Many organizations use JavaScript security analyzers to test for and remediate these vulnerabilities.

JavaScript Security Analyzers

JavaScript security analyzers are JavaScript security tools that perform code analysis on client-side applications. These analyzers can typically test for JavaScript security vulnerabilities, issues in implementation, configuration errors and other risks that can be exploited by attackers. The Veracode platform provides JavaScript security analysis through its automated cloud-based service. Veracode assesses web applications and client-side technologies in a running environment in order to discover JavaScript security vulnerabilities and other issues.

# data[].attributes.attachment_link.description
JavaScript is a high-level, interpreted programming language that has been widely used since its release in 1995. JavaScript is currently the world's 11th most popular programming language. JavaScript is commonly used in dynamic web pages to provide extended functionalities such as form submission/validation, interactivity, animations, user activity tracking and more.

# data[].attributes.attachment_link.description
Lesson Code: http://www.developphp.com/video/CSS/Standard-Selectors Learn to use the standard selectors of CSS. These selectors are not part of any pseudo selector or combinator group, and they serve as the basis for all other selectors. In this video we demonstrate the universal selector, type selector, class selector, id selector and compound selections.

# data[].attributes.attachment_link.readable_text
In the last article, I described three ways to work with with images from a responsive design standpoint, discussing the best solution to adopt while serving properly-sized imagery to a variety of screen sizes. In today's article, I'll focus on imagery management from another point of view, that is cross-browser compatibility.

During the creation of a website - especially if your aim to make its structure responsive - one of the most important and frequent problems that a web designer has to face involves cross-browser compatibility, that is, compatibility across different browsers.

What does "compatibility" stands for? The designer of a website must ensure that their design works properly and that its appearance is error-free and functional on any platform used to view it. It 's definitely one of the most complicated and frustrating aspects you must consider when designing a new project, but it's essential that the you do not leave anything to chance and keep cross-browser compatibility in mind throughout the design process.

Many of the new CSS capabilities introduced in the new CSS3 version are still not widely supported by all major browsers. In fact, some are not recognized and therefore ignored completely, which can pose major problems if your design relied on unsupported CSS. It's not just a variety of browser types either; different versions of the same browser can support (or fail to support) various design techniques, which complicates cross-browser compatibility even further.

Let's get back to image management, which probably is the weak point of the RWD approach, especially for browser compatibility issues. Photos and media need to be flexible and adapt to different devices, and at the same time, it's crucial that they don't slow down page loading in the process. Therefore, there is still no definitive, ideal solution to problems such as different screen sizes, restricted bandwidth (in cases of mobile browsing), performance on high-resolution ("retina") displays, and so on.

It is clear that using a single image (the largest possible version) for all devices is not an advisable solution. Think about the time a poor smartphone-2G user would take to load your design. After your ultra-slow image loads, those high-resolution images will probably display at about one quarter of their original size.

The largest problem is that media queries do not work with older browsers. Consequently, a responsive web page with many CSS3 rules applied can be seen correctly only by those who have recently-updated browsers with strong CSS3 support. Fortunately, there are three JavaScript solutions that can help us serve responsive websites to older browsers lacking CSS3 support: Respond.js, Modernizr, and adaptive.960.js. Let's have a look together.

Respond.js

The first solution is also the simplest one - I'm talking about a script called respond.js, which enables the older browser versions to understand and execute CSS3 media queries. Here's all it takes to get started.

This script is called on the page (as shown above) and adds support to media queries, min-width, max-width, and all media types (e.g. screen) for older browsers. This script can help your CSS3 instructions work properly, even for older browsers.

Respond.js may seem like it's too easy to be an ideal solution, but for many projects this is an great solution because the code is read from the latest CSS3 PC browser and all browser designed for smartphones. The sole purpose of the script is to make older browsers read the CSS3 instructions within media queries. Nothing more, nothing less.

Modernizr

The second solution is the use of a tool called Modernizr. As explained in the documentation page of its website, "Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation web technologies, i.e. features that stem from the HTML5 and CSS3 specifications."

Many of these features are already implemented in at least one major browser (most of them in two or more), and what Modernizr does is-very simply-tells you whether the current browser has this feature natively implemented or not. This is an indispensable tool that gives you fine control over the experience through JavaScript-driven feature detection.

After the first phase of detecting features, Modernizr creates a JavaScript object with the results and adds classes to the HTML element for you to target with your CSS. It's a gorgeous solution, because it makes it easy for you to write conditional JavaScript and CSS to handle each situation, whether a browser supports a feature or not.

Modernizr supports these browsers: IE6+, Firefox 3.5+, Opera 9.6+, Safari 2+, Chrome, Mobile Safari, Android WebKit browser, Opera Mobile, and Firefox Mobile.

You can download the full version of the library and implement it according to your specifications. However, if you only needs to test the compatibility of CSS3 in your browser, you can set the various options offered by the library and create your own compressed code. Paste the code into an external .js file and include it at the tag of your HTML document. The Modernizr team recommend to include the library just after importing CSS.

You should have this code:

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Your title</title> <script type="text/javascript" src="modernizr-latest.js""></script> </head> <body>Your content</body> </html>

Now you have a JavaScript library that indicates you whether the CSS3 or HTML5 functions you used are supported or not. Let the page run on the browser and look at the code with Chrome developer tools or Firebug.

You should see something like this:

adapt.960.js

The third solution that we consider is very different from the previous two, especially because it does not make use of CSS3 and accordingly of media queries. However, the concept is very similar to the CSS3 media queries.

If we use CSS3 in a single file, this library requires us to separate the code into several CSS files, one for each device type. The library parses the resolution of the device and calls the CSS designed for that specific screen resolution.

We can download the script and see immediately how it works. Activate the library on your page with the following line:

Then, copy the following code:

<script type="text/javascript"> var ADAPT_CONFIG = { // Where is your CSS? path: 'assets/css/', dynamic: true, callback: myCallback, range: [ '0px to 760px = mobile.css', '760px to 980px = 720.css', '980px to 1280px = 960.css', '1280px to 1600px = 1200.css', '1600px to 1920px = 1560.css', '1940px to 2540px = 1920.css', '2540px = 2520.css' ] }; </script>

We see the list of CSS files within the "range," one for each group of resolutions. Each of these files contains CSS properties related only to a specific device, just as the code enclosed within the CSS media queries.

The common CSS-that is the CSS that should apply to all screen sizes-should be included in a different CSS file, which for convenience we can call master.css and retrieve it before the integration of this library, just like normal CSS file:

Conclusion

Which of the three solutions should we adopt? They are all valid, sensible approaches. If you choose to apply the first solution (respond.js), you'll have to write and manage a single CSS file, unlike adapt.960.js, which requires multiple CSS files. Finally, if you choose to try Modernizr, you'll take advantage of new CSS3 capabilities in the browsers that can support them and still have easy and reliable means of controlling the situation for the browsers that cannot.

If you believe that, within few years, older browsers will be irrelevant and that mobile browsers will supersede their desktop counterparts, I believe that it is better to work with media queries and extend support for older browsers with JavaScripts plugins that are available.

Remember that there are also web-based services to test a responsive website and simulate resizing of the browser window. Two of these are responsive.is, which is very easy to use, and studiopress.com, which, after entering the web address, makes different views of your website appear side-by-side.

In addition to web-based solutions, there are also applications that can be installed directly on your personal computer. Among them, we find Opera Mobile Emulator, which is available for Mac, Linux, and Windows. After installing and opening the application, you'll have a list of devices that it can emulate (with the unfortunate exception of Apple devices).

To conclude this article, I'd like to share a very useful online tool to test the compatibility of your live website: crossbrowsertesting.com. You must choose an operating system and a web browser, and that's all. A series of well-organized screenshots on multiple browsers will allow you to have a complete view of your site, and in this way, it will be easier to understand on which elements you should modify to make your project perfectly compatible with any platform.
Want to learn more about Responsive Web Design? Check out SitePoint's new book, Jump Start Responsive Web Design!

# data[].attributes.attachment_link.title
Understanding Responsive Web Design: Cross-browser Compatibility - SitePoint

# data[].attributes.attachment_link.description
Understanding Responsive Web DesignResponsive Web Design: Using Fonts ResponsivelyUnderstanding Responsive Web Design: Clear Concepts and Practical ApplicationsResponsive Web Design: Fluid LayoutsResponsive Web Design: Custom Grid LayoutsUnderstanding Responsive Web Design: Responsive ImageryUnderstanding Responsive Web Design: Cross-browser CompatibilityIn the last article, I described three ways to work with with images from a responsive design standpoint, discussing the ...

# data[].attributes.attachment_link.provider_name
HTML5 Rocks - A resource for open web HTML5 developers

# data[].attributes.attachment_link.readable_text
Web browsers are the most widely used software. In this primer, I will explain how they work behind the scenes. We will see what happens when you type google.com in the address bar until you see the Google page on the browser screen.

The browsers we will talk about

There are five major browsers used on desktop today: Chrome, Internet Explorer, Firefox, Safari and Opera. On mobile, the main browsers are Android Browser, iPhone, Opera Mini and Opera Mobile, UC Browser, the Nokia S40/S60 browsers and Chrome-all of which, except for the Opera browsers, are based on WebKit. I will give examples from the open source browsers Firefox and Chrome, and Safari (which is partly open source). According to StatCounter statistics (as of June 2013) Chrome, Firefox and Safari make up around 71% of global desktop browser usage. On mobile, Android Browser, iPhone and Chrome constitute around 54% of usage.

The browser's main functionality

The main function of a browser is to present the web resource you choose, by requesting it from the server and displaying it in the browser window. The resource is usually an HTML document, but may also be a PDF, image, or some other type of content. The location of the resource is specified by the user using a URI (Uniform Resource Identifier).

The way the browser interprets and displays HTML files is specified in the HTML and CSS specifications. These specifications are maintained by the W3C (World Wide Web Consortium) organization, which is the standards organization for the web. For years browsers conformed to only a part of the specifications and developed their own extensions. That caused serious compatibility issues for web authors. Today most of the browsers more or less conform to the specifications.

Browser user interfaces have a lot in common with each other. Among the common user interface elements are:

Address bar for inserting a URI

Back and forward buttons

Bookmarking options

Refresh and stop buttons for refreshing or stopping the loading of current documents

Home button that takes you to your home page

Strangely enough, the browser's user interface is not specified in any formal specification, it just comes from good practices shaped over years of experience and by browsers imitating each other. The HTML5 specification doesn't define UI elements a browser must have, but lists some common elements. Among those are the address bar, status bar and tool bar. There are, of course, features unique to a specific browser like Firefox's downloads manager.

The browser's high level structure

The browser's main components are ( 1.1):

1. The user interface: this includes the address bar, back/forward button, bookmarking menu, etc. Every part of the browser display except the window where you see the requested page.

2. The browser engine: marshals actions between the UI and the rendering engine.

3. The rendering engine : responsible for displaying requested content. For example if the requested content is HTML, the rendering engine parses HTML and CSS, and displays the parsed content on the screen.

4. Networking: for network calls such as HTTP requests, using different implementations for different platform behind a platform-independent interface.

5. UI backend: used for drawing basic widgets like combo boxes and windows. This backend exposes a generic interface that is not platform specific. Underneath it uses operating system user interface methods.

6. JavaScript interpreter. Used to parse and execute JavaScript code.

7. Data storage. This is a persistence layer. The browser may need to save all sorts of data locally, such as cookies. Browsers also support storage mechanisms such as localStorage, IndexedDB, WebSQL and FileSystem.

It is important to note that browsers such as Chrome run multiple instances of the rendering engine: one for each tab. Each tab runs in a separate process.

The rendering engine

The responsibility of the rendering engine is well... Rendering, that is display of the requested contents on the browser screen.

By default the rendering engine can display HTML and XML documents and images. It can display other types of data via plug-ins or extension; for example, displaying PDF documents using a PDF viewer plug-in. However, in this chapter we will focus on the main use case: displaying HTML and images that are formatted using CSS.

Rendering engines

Different browsers use different rendering engines: Internet Explorer uses Trident, Firefox uses Gecko, Safari uses WebKit. Chrome and Opera (from version 15) use Blink, a fork of WebKit.

WebKit is an open source rendering engine which started as an engine for the Linux platform and was modified by Apple to support Mac and Windows. See webkit.org for more details.

The main flow

The rendering engine will start getting the contents of the requested document from the networking layer. This will usually be done in 8kB chunks.

After that, this is the basic flow of the rendering engine:

The rendering engine will start parsing the HTML document and convert elements to DOM nodes in a tree called the "content tree". The engine will parse the style data, both in external CSS files and in style elements. Styling information together with visual instructions in the HTML will be used to create another tree: the render tree.

The render tree contains rectangles with visual attributes like color and dimensions. The rectangles are in the right order to be displayed on the screen.

After the construction of the render tree it goes through a " layout" process. This means giving each node the exact coordinates where it should appear on the screen. The next stage is painting -the render tree will be traversed and each node will be painted using the UI backend layer.

It's important to understand that this is a gradual process. For better user experience, the rendering engine will try to display contents on the screen as soon as possible. It will not wait until all HTML is parsed before starting to build and layout the render tree. Parts of the content will be parsed and displayed, while the process continues with the rest of the contents that keeps coming from the network.

Main flow examples

Figure : Mozilla's Gecko rendering engine main flow (3.6)

From figures 3 and 4 you can see that although WebKit and Gecko use slightly different terminology, the flow is basically the same.

Gecko calls the tree of visually formatted elements a "Frame tree". Each element is a frame. WebKit uses the term "Render Tree" and it consists of "Render Objects". WebKit uses the term "layout" for the placing of elements, while Gecko calls it "Reflow". "Attachment" is WebKit's term for connecting DOM nodes and visual information to create the render tree. A minor non-semantic difference is that Gecko has an extra layer between the HTML and the DOM tree. It is called the "content sink" and is a factory for making DOM elements. We will talk about each part of the flow:

Parsing-general

Since parsing is a very significant process within the rendering engine, we will go into it a little more deeply. Let's begin with a little introduction about parsing.

Parsing a document means translating it to a structure the code can use. The result of parsing is usually a tree of nodes that represent the structure of the document. This is called a parse tree or a syntax tree.

For example, parsing the expression 2 + 3 - 1 could return this tree:

Grammars

Parsing is based on the syntax rules the document obeys: the language or format it was written in. Every format you can parse must have deterministic grammar consisting of vocabulary and syntax rules. It is called a context free grammar. Human languages are not such languages and therefore cannot be parsed with conventional parsing techniques.

Parser-Lexer combination

Parsing can be separated into two sub processes: lexical analysis and syntax analysis.

Lexical analysis is the process of breaking the input into tokens. Tokens are the language vocabulary: the collection of valid building blocks. In human language it will consist of all the words that appear in the dictionary for that language.

Syntax analysis is the applying of the language syntax rules.

Parsers usually divide the work between two components: the lexer (sometimes called tokenizer) that is responsible for breaking the input into valid tokens, and the parser that is responsible for constructing the parse tree by analyzing the document structure according to the language syntax rules. The lexer knows how to strip irrelevant characters like white spaces and line breaks.

The parsing process is iterative. The parser will usually ask the lexer for a new token and try to match the token with one of the syntax rules. If a rule is matched, a node corresponding to the token will be added to the parse tree and the parser will ask for another token.

If no rule matches, the parser will store the token internally, and keep asking for tokens until a rule matching all the internally stored tokens is found. If no rule is found then the parser will raise an exception. This means the document was not valid and contained syntax errors.

Translation

In many cases the parse tree is not the final product. Parsing is often used in translation: transforming the input document to another format. An example is compilation. The compiler that compiles source code into machine code first parses it into a parse tree and then translates the tree into a machine code document.

Parsing example

In figure 5 we built a parse tree from a mathematical expression. Let's try to define a simple mathematical language and see the parse process.

Vocabulary: Our language can include integers, plus signs and minus signs.

Syntax:

1. The language syntax building blocks are expressions, terms and operations.

2. Our language can include any number of expressions.

3. An expression is defined as a "term" followed by an "operation" followed by another term

4. An operation is a plus token or a minus token

5. A term is an integer token or an expression

Let's analyze the input 2 + 3 - 1.
The first substring that matches a rule is 2: according to rule #5 it is a term. The second match is 2 + 3: this matches the third rule: a term followed by an operation followed by another term. The next match will only be hit at the end of the input. 2 + 3 - 1 is an expression because we already know that 2 + 3 is a term, so we have a term followed by an operation followed by another term. 2 + + will not match any rule and therefore is an invalid input.

Formal definitions for vocabulary and syntax

Vocabulary is usually expressed by regular expressions.

For example our language will be defined as:

INTEGER: 0|[1-9][0-9]*
PLUS: +
MINUS: -

As you see, integers are defined by a regular expression.

Syntax is usually defined in a format called BNF. Our language will be defined as:

expression :=  term  operation  term
operation :=  PLUS | MINUS
term := INTEGER | expression

We said that a language can be parsed by regular parsers if its grammar is a context free grammar. An intuitive definition of a context free grammar is a grammar that can be entirely expressed in BNF. For a formal definition see Wikipedia's article on Context-free grammar

Types of parsers

There are two types of parsers: top down parsers and bottom up parsers. An intuitive explanation is that top down parsers examine the high level structure of the syntax and try to find a rule match. Bottom up parsers start with the input and gradually transform it into the syntax rules, starting from the low level rules until high level rules are met.

Let's see how the two types of parsers will parse our example.

The top down parser will start from the higher level rule: it will identify 2 + 3 as an expression. It will then identify 2 + 3 - 1 as an expression (the process of identifying the expression evolves, matching the other rules, but the start point is the highest level rule).

The bottom up parser will scan the input until a rule is matched. It will then replace the matching input with the rule. This will go on until the end of the input. The partly matched expression is placed on the parser's stack.

This type of bottom up parser is called a shift-reduce parser, because the input is shifted to the right (imagine a pointer pointing first at the input start and moving to the right) and is gradually reduced to syntax rules.

Generating parsers automatically

There are tools that can generate a parser. You feed them the grammar of your language-its vocabulary and syntax rules-and they generate a working parser. Creating a parser requires a deep understanding of parsing and it's not easy to create an optimized parser by hand, so parser generators can be very useful.

WebKit uses two well known parser generators: Flex for creating a lexer and Bison for creating a parser (you might run into them with the names Lex and Yacc). Flex input is a file containing regular expression definitions of the tokens. Bison's input is the language syntax rules in BNF format.

HTML Parser

The job of the HTML parser is to parse the HTML markup into a parse tree.

The HTML grammar definition

The vocabulary and syntax of HTML are defined in specifications created by the W3C organization.

Not a context free grammar

As we have seen in the parsing introduction, grammar syntax can be defined formally using formats like BNF.

Unfortunately all the conventional parser topics do not apply to HTML (I didn't bring them up just for fun-they will be used in parsing CSS and JavaScript). HTML cannot easily be defined by a context free grammar that parsers need.

There is a formal format for defining HTML-DTD (Document Type Definition)-but it is not a context free grammar.

This appears strange at first sight; HTML is rather close to XML. There are lots of available XML parsers. There is an XML variation of HTML-XHTML-so what's the big difference?

The difference is that the HTML approach is more "forgiving": it lets you omit certain tags (which are then added implicitly), or sometimes omit start or end tags, and so on. On the whole it's a "soft" syntax, as opposed to XML's stiff and demanding syntax.

This seemingly small detail makes a world of a difference. On one hand this is the main reason why HTML is so popular: it forgives your mistakes and makes life easy for the web author. On the other hand, it makes it difficult to write a formal grammar. So to summarize, HTML cannot be parsed easily by conventional parsers, since its grammar is not context free. HTML cannot be parsed by XML parsers.

HTML DTD

HTML definition is in a DTD format. This format is used to define languages of the SGML family. The format contains definitions for all allowed elements, their attributes and hierarchy. As we saw earlier, the HTML DTD doesn't form a context free grammar.

There are a few variations of the DTD. The strict mode conforms solely to the specifications but other modes contain support for markup used by browsers in the past. The purpose is backwards compatibility with older content. The current strict DTD is here: www.w3.org/TR/html4/strict.dtd

DOM

The output tree (the "parse tree") is a tree of DOM element and attribute nodes. DOM is short for Document Object Model. It is the object presentation of the HTML document and the interface of HTML elements to the outside world like JavaScript.
The root of the tree is the " Document" object.

The DOM has an almost one-to-one relation to the markup. For example:

<html>
  <body>
    <p>
      Hello World
    </p>
    <div> <img src="example.png"/></div>
  </body>
</html>

This markup would be translated to the following DOM tree:

Like HTML, DOM is specified by the W3C organization. See www.w3.org/DOM/DOMTR. It is a generic specification for manipulating documents. A specific module describes HTML specific elements. The HTML definitions can be found here: www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/idl-definitions.html.

When I say the tree contains DOM nodes, I mean the tree is constructed of elements that implement one of the DOM interfaces. Browsers use concrete implementations that have other attributes used by the browser internally.

The parsing algorithm

As we saw in the previous sections, HTML cannot be parsed using the regular top down or bottom up parsers.

The reasons are:

1. The forgiving nature of the language.

2. The fact that browsers have traditional error tolerance to support well known cases of invalid HTML.

3. The parsing process is reentrant. For other languages, the source doesn't change during parsing, but in HTML, dynamic code (such as script elements containing document.write() calls) can add extra tokens, so the parsing process actually modifies the input.

Unable to use the regular parsing techniques, browsers create custom parsers for parsing HTML.

The parsing algorithm is described in detail by the HTML5 specification. The algorithm consists of two stages: tokenization and tree construction.

Tokenization is the lexical analysis, parsing the input into tokens. Among HTML tokens are start tags, end tags, attribute names and attribute values.

The tokenizer recognizes the token, gives it to the tree constructor, and consumes the next character for recognizing the next token, and so on until the end of the input.

The tokenization algorithm

The algorithm's output is an HTML token. The algorithm is expressed as a state machine. Each state consumes one or more characters of the input stream and updates the next state according to those characters. The decision is influenced by the current tokenization state and by the tree construction state. This means the same consumed character will yield different results for the correct next state, depending on the current state. The algorithm is too complex to describe fully, so let's see a simple example that will help us understand the principle.

Basic example-tokenizing the following HTML:

<html>
  <body>
    Hello world
  </body>
</html>

The initial state is the "Data state". When the < character is encountered, the state is changed to "Tag open state". Consuming an a-z character causes creation of a "Start tag token", the state is changed to "Tag name state". We stay in this state until the> character is consumed. Each character is appended to the new token name. In our case the created token is an html token.

When the > tag is reached, the current token is emitted and the state changes back to the "Data state". The<body> tag will be treated by the same steps. So far the html and body tags were emitted. We are now back at the "Data state". Consuming the H character of Hello world will cause creation and emitting of a character token, this goes on until the < of </body> is reached. We will emit a character token for each character of Hello world.

We are now back at the "Tag open state". Consuming the next input/ will cause creation of an end tag token and a move to the "Tag name state". Again we stay in this state until we reach >.Then the new tag token will be emitted and we go back to the "Data state". The</html> input will be treated like the previous case.

Tree construction algorithm

When the parser is created the Document object is created. During the tree construction stage the DOM tree with the Document in its root will be modified and elements will be added to it. Each node emitted by the tokenizer will be processed by the tree constructor. For each token the specification defines which DOM element is relevant to it and will be created for this token. The element is added to the DOM tree, and also the stack of open elements. This stack is used to correct nesting mismatches and unclosed tags. The algorithm is also described as a state machine. The states are called "insertion modes".

Let's see the tree construction process for the example input:

<html>
  <body>
    Hello world
  </body>
</html>

The input to the tree construction stage is a sequence of tokens from the tokenization stage. The first mode is the "initial mode". Receiving the "html" token will cause a move to the "before html" mode and a reprocessing of the token in that mode. This will cause creation of the HTMLHtmlElement element, which will be appended to the root Document object.

The state will be changed to "before head". The "body" token is then received. An HTMLHeadElement will be created implicitly although we don't have a "head" token and it will be added to the tree.

We now move to the "in head" mode and then to "after head". The body token is reprocessed, an HTMLBodyElement is created and inserted and the mode is transferred to "in body".

The character tokens of the "Hello world" string are now received. The first one will cause creation and insertion of a "Text" node and the other characters will be appended to that node.

The receiving of the body end token will cause a transfer to "after body" mode. We will now receive the html end tag which will move us to"after after body" mode. Receiving the end of file token will end the parsing.

Actions when the parsing is finished

At this stage the browser will mark the document as interactive and start parsing scripts that are in "deferred" mode: those that should be executed after the document is parsed. The document state will be then set to "complete" and a "load" event will be fired.

You can see the full algorithms for tokenization and tree construction in the HTML5 specification

Browsers' error tolerance

You never get an "Invalid Syntax" error on an HTML page. Browsers fix any invalid content and go on.

Take this HTML for example:

<html>
  <mytag>
  </mytag>
  <div>
  <p>
  </div>
    Really lousy HTML
  </p>
</html>

I must have violated about a million rules ("mytag" is not a standard tag, wrong nesting of the "p" and "div" elements and more) but the browser still shows it correctly and doesn't complain. So a lot of the parser code is fixing the HTML author mistakes.

Error handling is quite consistent in browsers, but amazingly enough it hasn't been part of HTML specifications. Like bookmarking and back/forward buttons it's just something that developed in browsers over the years. There are known invalid HTML constructs repeated on many sites, and the browsers try to fix them in a way conformant with other browsers.

The HTML5 specification does define some of these requirements. (WebKit summarizes this nicely in the comment at the beginning of the HTML parser class.)

The parser parses tokenized input into the document, building up the document tree. If the document is well-formed, parsing it is straightforward.

Unfortunately, we have to handle many HTML documents that are not well-formed, so the parser has to be tolerant about errors.

We have to take care of at least the following error conditions:

1. The element being added is explicitly forbidden inside some outer tag. In this case we should close all tags up to the one which forbids the element, and add it afterwards.

2. We are not allowed to add the element directly. It could be that the person writing the document forgot some tag in between (or that the tag in between is optional). This could be the case with the following tags: HTML HEAD BODY TBODY TR TD LI (did I forget any?).

3. We want to add a block element inside an inline element. Close all inline elements up to the next higher block element.

4. If this doesn't help, close elements until we are allowed to add the element-or ignore the tag.

Let's see some WebKit error tolerance examples:

</br> instead of <br>

Some sites use </br> instead of <br>. In order to be compatible with IE and Firefox, WebKit treats this like <br>.
The code:

if (t->isCloseTag(brTag) && m_document->inCompatMode()) {
     reportError(MalformedBRError);
     t->beginTag = true;
}

Note that the error handling is internal: it won't be presented to the user.

A stray table

A stray table is a table inside another table, but not inside a table cell.

For example:

<table>
    <table>
        <tr><td>inner table</td></tr>
    </table>
    <tr><td>outer table</td></tr>
</table>

WebKit will change the hierarchy to two sibling tables:

<table>
    <tr><td>outer table</td></tr>
</table>
<table>
    <tr><td>inner table</td></tr>
</table>

The code:

if (m_inStrayTableContent && localName == tableTag)
        popBlock(tableTag);

WebKit uses a stack for the current element contents: it will pop the inner table out of the outer table stack. The tables will now be siblings.

Nested form elements

In case the user puts a form inside another form, the second form is ignored.
The code:

if (!m_currentFormElement) {
        m_currentFormElement = new HTMLFormElement(formTag,    m_document);
}

A too deep tag hierarchy

The comment speaks for itself.

bool HTMLParser::allowNestedRedundantTag(const AtomicString& tagName)
{

unsigned i = 0;
for (HTMLStackElem* curr = m_blockStack;
         i < cMaxRedundantTagDepth && curr && curr->tagName == tagName;
     curr = curr->next, i++) { }
return i != cMaxRedundantTagDepth;
}

Misplaced html or body end tags

Again-the comment speaks for itself.

Support for really broken HTML. We never close the body tag, since some stupid web pages close it before the actual end of the doc. Let's rely on the end() call to close things.

if (t->tagName == htmlTag || t->tagName == bodyTag )
        return;

So web authors beware-unless you want to appear as an example in a WebKit error tolerance code snippet-write well formed HTML.

CSS parsing

Remember the parsing concepts in the introduction? Well, unlike HTML, CSS is a context free grammar and can be parsed using the types of parsers described in the introduction. In fact the CSS specification defines CSS lexical and syntax grammar.

Let's see some examples:
The lexical grammar (vocabulary) is defined by regular expressions for each token:

comment   \/\*[^*]*\*+([^/*][^*]*\*+)*\/
num   [0-9]+|[0-9]*"."[0-9]+
nonascii  [\200-\377]
nmstart   [_a-z]|{nonascii}|{escape}
nmchar    [_a-z0-9-]|{nonascii}|{escape}
name    {nmchar}+
ident   {nmstart}{nmchar}*

"ident" is short for identifier, like a class name. "name" is an element id (that is referred by "#" )

The syntax grammar is described in BNF.

ruleset
  : selector [ ',' S* selector ]*
    '{' S* declaration [ ';' S* declaration ]* '}' S*
  ;
selector
  : simple_selector [ combinator selector | S+ [ combinator? selector ]? ]?
  ;
simple_selector
  : element_name [ HASH | class | attrib | pseudo ]*
  | [ HASH | class | attrib | pseudo ]+
  ;
class
  : '.' IDENT
  ;
element_name
  : IDENT | '*'
  ;
attrib
  : '[' S* IDENT S* [ [ '=' | INCLUDES | DASHMATCH ] S*
    [ IDENT | STRING ] S* ] ']'
  ;
pseudo
  : ':' [ IDENT | FUNCTION S* [IDENT S*] ')' ]
  ;

Explanation: A ruleset is this structure:

div.error, a.error {
  color:red;
  font-weight:bold;
}

div.error and a.error are selectors. The part inside the curly braces contains the rules that are applied by this ruleset. This structure is defined formally in this definition:

ruleset
  : selector [ ',' S* selector ]*
    '{' S* declaration [ ';' S* declaration ]* '}' S*
  ;

This means a ruleset is a selector or optionally a number of selectors separated by a comma and spaces (S stands for white space). A ruleset contains curly braces and inside them a declaration or optionally a number of declarations separated by a semicolon. "declaration" and "selector" will be defined in the following BNF definitions.

WebKit CSS parser

WebKit uses Flex and Bison parser generators to create parsers automatically from the CSS grammar files. As you recall from the parser introduction, Bison creates a bottom up shift-reduce parser. Firefox uses a top down parser written manually. In both cases each CSS file is parsed into a StyleSheet object. Each object contains CSS rules. The CSS rule objects contain selector and declaration objects and other objects corresponding to CSS grammar.

The order of processing scripts and style sheets

Scripts

The model of the web is synchronous. Authors expect scripts to be parsed and executed immediately when the parser reaches a <script> tag. The parsing of the document halts until the script has been executed. If the script is external then the resource must first be fetched from the network-this is also done synchronously, and parsing halts until the resource is fetched. This was the model for many years and is also specified in HTML4 and 5 specifications. Authors can add the "defer" attribute to a script, in which case it will not halt document parsing and will execute after the document is parsed. HTML5 adds an option to mark the script as asynchronous so it will be parsed and executed by a different thread.

Speculative parsing

Both WebKit and Firefox do this optimization. While executing scripts, another thread parses the rest of the document and finds out what other resources need to be loaded from the network and loads them. In this way, resources can be loaded on parallel connections and overall speed is improved. Note: the speculative parser only parses references to external resources like external scripts, style sheets and images: it doesn't modify the DOM tree-that is left to the main parser.

Style sheets

Style sheets on the other hand have a different model. Conceptually it seems that since style sheets don't change the DOM tree, there is no reason to wait for them and stop the document parsing. There is an issue, though, of scripts asking for style information during the document parsing stage. If the style is not loaded and parsed yet, the script will get wrong answers and apparently this caused lots of problems. It seems to be an edge case but is quite common. Firefox blocks all scripts when there is a style sheet that is still being loaded and parsed. WebKit blocks scripts only when they try to access certain style properties that may be affected by unloaded style sheets.

Render tree construction

While the DOM tree is being constructed, the browser constructs another tree, the render tree. This tree is of visual elements in the order in which they will be displayed. It is the visual representation of the document. The purpose of this tree is to enable painting the contents in their correct order.

Firefox calls the elements in the render tree "frames". WebKit uses the term renderer or render object.
A renderer knows how to lay out and paint itself and its children.
WebKit's RenderObject class, the base class of the renderers, has the following definition:

class RenderObject{
  virtual void layout();
  virtual void paint(PaintInfo);
  virtual void rect repaintRect();
  Node* node;  //the DOM node
  RenderStyle* style;  // the computed style
  RenderLayer* containgLayer; //the containing z-index layer
}

Each renderer represents a rectangular area usually corresponding to a node's CSS box, as described by the CSS2 spec. It includes geometric information like width, height and position.
The box type is affected by the "display" value of the style attribute that is relevant to the node (see the style computation section). Here is WebKit code for deciding what type of renderer should be created for a DOM node, according to the display attribute:

RenderObject* RenderObject::createObject(Node* node, RenderStyle* style)
{
    Document* doc = node->document();
    RenderArena* arena = doc->renderArena();
    ...
    RenderObject* o = 0;

    switch (style->display()) {
        case NONE:
            break;
        case INLINE:
            o = new (arena) RenderInline(node);
            break;
        case BLOCK:
            o = new (arena) RenderBlock(node);
            break;
        case INLINE_BLOCK:
            o = new (arena) RenderBlock(node);
            break;
        case LIST_ITEM:
            o = new (arena) RenderListItem(node);
            break;
       ...
    }

    return o;
}

The element type is also considered: for example, form controls and tables have special frames.
In WebKit if an element wants to create a special renderer, it will override the createRenderer() method. The renderers point to style objects that contains non geometric information.

The render tree relation to the DOM tree

The renderers correspond to DOM elements, but the relation is not one to one. Non-visual DOM elements will not be inserted in the render tree. An example is the "head" element. Also elements whose display value was assigned to "none" will not appear in the tree (whereas elements with "hidden" visibility will appear in the tree).

There are DOM elements which correspond to several visual objects. These are usually elements with complex structure that cannot be described by a single rectangle. For example, the "select" element has three renderers: one for the display area, one for the drop down list box and one for the button. Also when text is broken into multiple lines because the width is not sufficient for one line, the new lines will be added as extra renderers.
Another example of multiple renderers is broken HTML. According to the CSS spec an inline element must contain either only block elements or only inline elements. In the case of mixed content, anonymous block renderers will be created to wrap the inline elements.

Some render objects correspond to a DOM node but not in the same place in the tree. Floats and absolutely positioned elements are out of flow, placed in a different part of the tree, and mapped to the real frame. A placeholder frame is where they should have been.

Figure : The render tree and the corresponding DOM tree (3.1). The "Viewport" is the initial containing block. In WebKit it will be the "RenderView" object

The flow of constructing the tree

In Firefox, the presentation is registered as a listener for DOM updates. The presentation delegates frame creation to the FrameConstructor and the constructor resolves style (see style computation) and creates a frame.

In WebKit the process of resolving the style and creating a renderer is called "attachment". Every DOM node has an "attach" method. Attachment is synchronous, node insertion to the DOM tree calls the new node "attach" method.

Processing the html and body tags results in the construction of the render tree root. The root render object corresponds to what the CSS spec calls the containing block: the top most block that contains all other blocks. Its dimensions are the viewport: the browser window display area dimensions. Firefox calls it ViewPortFrame and WebKit calls it RenderView. This is the render object that the document points to. The rest of the tree is constructed as a DOM nodes insertion.

See the CSS2 spec on the processing model.

Style Computation

Building the render tree requires calculating the visual properties of each render object. This is done by calculating the style properties of each element.

The style includes style sheets of various origins, inline style elements and visual properties in the HTML (like the "bgcolor" property).The later is translated to matching CSS style properties.

The origins of style sheets are the browser's default style sheets, the style sheets provided by the page author and user style sheets-these are style sheets provided by the browser user (browsers let you define your favorite styles. In Firefox, for instance, this is done by placing a style sheet in the "Firefox Profile" folder).

Style computation brings up a few difficulties:

1. Style data is a very large construct, holding the numerous style properties, this can cause memory problems.

2. Finding the matching rules for each element can cause performance issues if it's not optimized. Traversing the entire rule list for each element to find matches is a heavy task. Selectors can have complex structure that can cause the matching process to start on a seemingly promising path that is proven to be futile and another path has to be tried.

For example-this compound selector:

div div div div{
  ...
}

Means the rules apply to a <div> who is the descendant of 3 divs. Suppose you want to check if the rule applies for a given <div> element. You choose a certain path up the tree for checking. You may need to traverse the node tree up just to find out there are only two divs and the rule does not apply. You then need to try other paths in the tree.

3. Applying the rules involves quite complex cascade rules that define the hierarchy of the rules.

Let's see how the browsers face these issues:
Sharing style data

WebKit nodes references style objects (RenderStyle) These objects can be shared by nodes in some conditions. The nodes are siblings or cousins and:

1. The elements must be in the same mouse state (e.g., one can't be in :hover while the other isn't)

2. Neither element should have an id

3. The tag names should match

4. The class attributes should match

5. The set of mapped attributes must be identical

6. The link states must match

7. The focus states must match

8. Neither element should be affected by attribute selectors, where affected is defined as having any selector match that uses an attribute selector in any position within the selector at all

9. There must be no inline style attribute on the elements

10. There must be no sibling selectors in use at all. WebCore simply throws a global switch when any sibling selector is encountered and disables style sharing for the entire document when they are present. This includes the + selector and selectors like :first-child and :last-child.

Firefox rule tree

Firefox has two extra trees for easier style computation: the rule tree and style context tree. WebKit also has style objects but they are not stored in a tree like the style context tree, only the DOM node points to its relevant style.

Figure : Firefox style context tree(2.2)

The style contexts contain end values. The values are computed by applying all the matching rules in the correct order and performing manipulations that transform them from logical to concrete values. For example, if the logical value is a percentage of the screen it will be calculated and transformed to absolute units. The rule tree idea is really clever. It enables sharing these values between nodes to avoid computing them again. This also saves space.

All the matched rules are stored in a tree. The bottom nodes in a path have higher priority. The tree contains all the paths for rule matches that were found. Storing the rules is done lazily. The tree isn't calculated at the beginning for every node, but whenever a node style needs to be computed the computed paths are added to the tree.

The idea is to see the tree paths as words in a lexicon. Lets say we already computed this rule tree:

Suppose we need to match rules for another element in the content tree, and find out the matched rules (in the correct order) are B-E-I. We already have this path in the tree because we already computed path A-B-E-I-L. We will now have less work to do.

Let's see how the tree saves us work.

Division into structs

The style contexts are divided into structs. Those structs contain style information for a certain category like border or color. All the properties in a struct are either inherited or non inherited. Inherited properties are properties that unless defined by the element, are inherited from its parent. Non inherited properties (called "reset" properties) use default values if not defined.

The tree helps us by caching entire structs (containing the computed end values) in the tree. The idea is that if the bottom node didn't supply a definition for a struct, a cached struct in an upper node can be used.

Computing the style contexts using the rule tree

When computing the style context for a certain element, we first compute a path in the rule tree or use an existing one. We then begin to apply the rules in the path to fill the structs in our new style context. We start at the bottom node of the path-the one with the highest precedence (usually the most specific selector) and traverse the tree up until our struct is full. If there is no specification for the struct in that rule node, then we can greatly optimize-we go up the tree until we find a node that specifies it fully and simply point to it-that's the best optimization-the entire struct is shared. This saves computation of end values and memory.
If we find partial definitions we go up the tree until the struct is filled.

If we didn't find any definitions for our struct then, in case the struct is an "inherited" type, we point to the struct of our parent in the context tree. In this case we also succeeded in sharing structs. If it's a reset struct then default values will be used.

If the most specific node does add values then we need to do some extra calculations for transforming it to actual values. We then cache the result in the tree node so it can be used by children.

In case an element has a sibling or a brother that points to the same tree node then the entire style context can be shared between them.

Lets see an example: Suppose we have this HTML

<html>
  <body>
    <div class="err" id="div1">
      <p>
        this is a <span class="big"> big error </span>
        this is also a
        <span class="big"> very  big  error</span> error
      </p>
    </div>
    <div class="err" id="div2">another error</div>
  </body>
</html>

And the following rules:

div {margin:5px;color:black}
.err {color:red}
.big {margin-top:3px}
div span {margin-bottom:4px}
#div1 {color:blue}
#div2 {color:green}

To simplify things let's say we need to fill out only two structs: the color struct and the margin struct. The color struct contains only one member: the color The margin struct contains the four sides.
The resulting rule tree will look like this (the nodes are marked with the node name: the number of the rule they point at):

Figure : The rule tree

The context tree will look like this (node name: rule node they point to):

Figure : The context tree

Suppose we parse the HTML and get to the second <div> tag. We need to create a style context for this node and fill its style structs.
We will match the rules and discover that the matching rules for the <div> are 1, 2 and 6. This means there is already an existing path in the tree that our element can use and we just need to add another node to it for rule 6 (node F in the rule tree).
We will create a style context and put it in the context tree. The new style context will point to node F in the rule tree.

We now need to fill the style structs. We will begin by filling out the margin struct. Since the last rule node (F) doesn't add to the margin struct, we can go up the tree until we find a cached struct computed in a previous node insertion and use it. We will find it on node B, which is the uppermost node that specified margin rules.

We do have a definition for the color struct, so we can't use a cached struct. Since color has one attribute we don't need to go up the tree to fill other attributes. We will compute the end value (convert string to RGB etc) and cache the computed struct on this node.

The work on the second <span> element is even easier. We will match the rules and come to the conclusion that it points to rule G, like the previous span. Since we have siblings that point to the same node, we can share the entire style context and just point to the context of the previous span.

For structs that contain rules that are inherited from the parent, caching is done on the context tree (the color property is actually inherited, but Firefox treats it as reset and caches it on the rule tree).
For instance if we added rules for fonts in a paragraph:

p {font-family: Verdana; font size: 10px; font-weight: bold}

Then the paragraph element, which is a child of the div in the context tree, could have shared the same font struct as his parent. This is if no font rules where specified for the paragraph.

In WebKit, who does not have a rule tree, the matched declarations are traversed four times. First non-important high priority properties are applied (properties that should be applied first because others depend on them, such as display), then high priority important, then normal priority non-important, then normal priority important rules. This means that properties that appear multiple times will be resolved according to the correct cascade order. The last wins.

So to summarize: sharing the style objects (entirely or some of the structs inside them) solves issues 1 and 3. The Firefox rule tree also helps in applying the properties in the correct order.

Manipulating the rules for an easy match

There are several sources for style rules:

CSS rules, either in external style sheets or in style elements.

p {color: blue}

Inline style attributes like

<p style="color: blue" />

HTML visual attributes (which are mapped to relevant style rules)

<p bgcolor="blue" />

The last two are easily matched to the element since he owns the style attributes and HTML attributes can be mapped using the element as the key.

As noted previously in issue #2, the CSS rule matching can be trickier. To solve the difficulty, the rules are manipulated for easier access.

After parsing the style sheet, the rules are added to one of several hash maps, according to the selector. There are maps by id, by class name, by tag name and a general map for anything that doesn't fit into those categories. If the selector is an id, the rule will be added to the id map, if it's a class it will be added to the class map etc.
This manipulation makes it much easier to match rules. There is no need to look in every declaration: we can extract the relevant rules for an element from the maps. This optimization eliminates 95+% of the rules, so that they need not even be considered during the matching process( 4.1).

Let's see for example the following style rules:

p.error {color: red}
#messageDiv {height: 50px}
div {margin: 5px}

The first rule will be inserted into the class map. The second into the id map and the third into the tag map.
For the following HTML fragment;

<p class="error">an error occurred </p>
<div id=" messageDiv">this is a message</div>

We will first try to find rules for the p element. The class map will contain an "error" key under which the rule for "p.error" is found. The div element will have relevant rules in the id map (the key is the id) and the tag map. So the only work left is finding out which of the rules that were extracted by the keys really match.
For example if the rule for the div was

table div {margin: 5px}

it will still be extracted from the tag map, because the key is the rightmost selector, but it would not match our div element, who does not have a table ancestor.

Both WebKit and Firefox do this manipulation.

Applying the rules in the correct cascade order

The style object has properties corresponding to every visual attribute (all CSS attributes but more generic). If the property is not defined by any of the matched rules, then some properties can be inherited by the parent element style object. Other properties have default values.

The problem begins when there is more than one definition-here comes the cascade order to solve the issue.

Style sheet cascade order

A declaration for a style property can appear in several style sheets, and several times inside a style sheet. This means the order of applying the rules is very important. This is called the "cascade" order. According to CSS2 spec, the cascade order is (from low to high):

1. Browser declarations

2. User normal declarations

3. Author normal declarations

4. Author important declarations

5. User important declarations

The browser declarations are least important and the user overrides the author only if the declaration was marked as important. Declarations with the same order will be sorted by specificity and then the order they are specified. The HTML visual attributes are translated to matching CSS declarations . They are treated as author rules with low priority.

Specificity

The selector specificity is defined by the CSS2 specification as follows:

count 1 if the declaration it is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a)

count the number of ID attributes in the selector (= b)

count the number of other attributes and pseudo-classes in the selector (= c)

count the number of element names and pseudo-elements in the selector (= d)

Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.
The number base you need to use is defined by the highest count you have in one of the categories.
For example, if a=14 you can use hexadecimal base. In the unlikely case where a=17 you will need a 17 digits number base. The later situation can happen with a selector like this: html body div div p ... (17 tags in your selector.. not very likely).

Some examples:

 *             {}  /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */
 li            {}  /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */
 li:first-line {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
 ul li         {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
 ul ol+li      {}  /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */
 h1 + *[rel=up]{}  /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */
 ul ol li.red  {}  /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */
 li.red.level  {}  /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */
 #x34y         {}  /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */
 style=""          /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */

Sorting the rules

After the rules are matched, they are sorted according to the cascade rules. WebKit uses bubble sort for small lists and merge sort for big ones. WebKit implements sorting by overriding the ">" operator for the rules:

static bool operator >(CSSRuleData& r1, CSSRuleData& r2)
{
    int spec1 = r1.selector()->specificity();
    int spec2 = r2.selector()->specificity();
    return (spec1 == spec2) : r1.position() > r2.position() : spec1 > spec2;
}

Gradual process

WebKit uses a flag that marks if all top level style sheets (including @imports) have been loaded. If the style is not fully loaded when attaching, place holders are used and it is marked in the document, and they will be recalculated once the style sheets were loaded.

Layout

When the renderer is created and added to the tree, it does not have a position and size. Calculating these values is called layout or reflow.

HTML uses a flow based layout model, meaning that most of the time it is possible to compute the geometry in a single pass. Elements later ``in the flow'' typically do not affect the geometry of elements that are earlier ``in the flow'', so layout can proceed left-to-right, top-to-bottom through the document. There are exceptions: for example, HTML tables may require more than one pass ( 3.5).

The coordinate system is relative to the root frame. Top and left coordinates are used.

Layout is a recursive process. It begins at the root renderer, which corresponds to the <html> element of the HTML document. Layout continues recursively through some or all of the frame hierarchy, computing geometric information for each renderer that requires it.

The position of the root renderer is 0,0 and its dimensions are the viewport-the visible part of the browser window.

All renderers have a "layout" or "reflow" method, each renderer invokes the layout method of its children that need layout.

Dirty bit system

In order not to do a full layout for every small change, browsers use a "dirty bit" system. A renderer that is changed or added marks itself and its children as "dirty": needing layout.

There are two flags: "dirty", and "children are dirty" which means that although the renderer itself may be OK, it has at least one child that needs a layout.

Global and incremental layout

Layout can be triggered on the entire render tree-this is "global" layout. This can happen as a result of:

1. A global style change that affects all renderers, like a font size change.

2. As a result of a screen being resized

Layout can be incremental, only the dirty renderers will be laid out (this can cause some damage which will require extra layouts).
Incremental layout is triggered (asynchronously) when renderers are dirty. For example when new renderers are appended to the render tree after extra content came from the network and was added to the DOM tree.

Figure : Incremental layout-only dirty renderers and their children are laid out (3.6)

Asynchronous and Synchronous layout

Incremental layout is done asynchronously. Firefox queues "reflow commands" for incremental layouts and a scheduler triggers batch execution of these commands. WebKit also has a timer that executes an incremental layout-the tree is traversed and "dirty" renderers are layout out.
Scripts asking for style information, like "offsetHeight" can trigger incremental layout synchronously.
Global layout will usually be triggered synchronously.
Sometimes layout is triggered as a callback after an initial layout because some attributes, like the scrolling position changed.

Optimizations

When a layout is triggered by a "resize" or a change in the renderer position(and not size), the renders sizes are taken from a cache and not recalculated..
In some cases only a sub tree is modified and layout does not start from the root. This can happen in cases where the change is local and does not affect its surroundings-like text inserted into text fields (otherwise every keystroke would trigger a layout starting from the root).

The layout process

The layout usually has the following pattern:

1. Parent renderer determines its own width.

2. Parent goes over children and:

1. Place the child renderer (sets its x and y).

2. Calls child layout if needed-they are dirty or we are in a global layout, or for some other reason-which calculates the child's height.

3. Parent uses children's accumulative heights and the heights of margins and padding to set its own height-this will be used by the parent renderer's parent.

4. Sets its dirty bit to false.

Firefox uses a "state" object(nsHTMLReflowState) as a parameter to layout (termed "reflow"). Among others the state includes the parents width.
The output of the Firefox layout is a "metrics" object(nsHTMLReflowMetrics). It will contain the renderer computed height.

Width calculation

The renderer's width is calculated using the container block's width, the renderer's style "width" property, the margins and borders.
For example the width of the following div:

<div style="width: 30%"/>

Would be calculated by WebKit as the following(class RenderBox method calcWidth): So far this was the calculation of the "preferred width". Now the minimum and maximum widths will be calculated.
If the preferred width is greater then the maximum width, the maximum width is used. If it is less then the minimum width (the smallest unbreakable unit) then the minimum width is used.

The values are cached in case a layout is needed, but the width does not change.

Line Breaking

When a renderer in the middle of a layout decides that it needs to break, the renderer stops and propagates to the layout's parent that it needs to be broken. The parent creates the extra renderers and calls layout on them.

Painting

In the painting stage, the render tree is traversed and the renderer's "paint()" method is called to display content on the screen. Painting uses the UI infrastructure component.

Global and Incremental

Like layout, painting can also be global-the entire tree is painted-or incremental. In incremental painting, some of the renderers change in a way that does not affect the entire tree. The changed renderer invalidates its rectangle on the screen. This causes the OS to see it as a "dirty region" and generate a "paint" event. The OS does it cleverly and coalesces several regions into one. In Chrome it is more complicated because the renderer is in a different process then the main process. Chrome simulates the OS behavior to some extent. The presentation listens to these events and delegates the message to the render root. The tree is traversed until the relevant renderer is reached. It will repaint itself (and usually its children).

The painting order

CSS2 defines the order of the painting process. This is actually the order in which the elements are stacked in the stacking contexts. This order affects painting since the stacks are painted from back to front. The stacking order of a block renderer is:

1. background color

2. background image

3. border

4. children

5. outline

Firefox display list

Firefox goes over the render tree and builds a display list for the painted rectangular. It contains the renderers relevant for the rectangular, in the right painting order (backgrounds of the renderers, then borders etc). That way the tree needs to be traversed only once for a repaint instead of several times-painting all backgrounds, then all images, then all borders etc.

Firefox optimizes the process by not adding elements that will be hidden, like elements completely beneath other opaque elements.

WebKit rectangle storage

Before repainting, WebKit saves the old rectangle as a bitmap. It then paints only the delta between the new and old rectangles.

Dynamic changes

The browsers try to do the minimal possible actions in response to a change. So changes to an elements color will cause only repaint of the element. Changes to the element position will cause layout and repaint of the element, its children and possibly siblings. Adding a DOM node will cause layout and repaint of the node. Major changes, like increasing font size of the "html" element, will cause invalidation of caches, relayout and repaint of the entire tree.

The rendering engine's threads

The rendering engine is single threaded. Almost everything, except network operations, happens in a single thread. In Firefox and Safari this is the main thread of the browser. In Chrome it's the tab process main thread.
Network operations can be performed by several parallel threads. The number of parallel connections is limited (usually 2-6 connections).

Event loop

The browser main thread is an event loop. It's an infinite loop that keeps the process alive. It waits for events (like layout and paint events) and processes them. This is Firefox code for the main event loop:

while (!mExiting)
    NS_ProcessNextEvent(thread);

CSS2 visual model

The canvas

According to the CSS2 specification, the term canvas describes "the space where the formatting structure is rendered": where the browser paints the content. The canvas is infinite for each dimension of the space but browsers choose an initial width based on the dimensions of the viewport.

According to www.w3.org/TR/CSS2/zindex.html, the canvas is transparent if contained within another, and given a browser defined color if it is not.

CSS Box model

The CSS box model describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model.
Each box has a content area (e.g. text, an image, etc.) and optional surrounding padding, border, and margin areas.

Figure : CSS2 box model

Each node generates 0..n such boxes.
All elements have a "display" property that determines the type of box that will be generated. Examples:

block: generates a block box.
inline: generates one or more inline boxes.
none: no box is generated.

The default is inline but the browser style sheet may set other defaults. For example: the default display for the "div" element is block.
You can find a default style sheet example here: www.w3.org/TR/CSS2/sample.html

Positioning scheme

There are three schemes:

1. Normal: the object is positioned according to its place in the document. This means its place in the render tree is like its place in the DOM tree and laid out according to its box type and dimensions

2. Float: the object is first laid out like normal flow, then moved as far left or right as possible

3. Absolute: the object is put in the render tree in a different place than in the DOM tree

The positioning scheme is set by the "position" property and the "float" attribute.

static and relative cause a normal flow

absolute and fixed cause absolute positioning

In static positioning no position is defined and the default positioning is used. In the other schemes, the author specifies the position: top, bottom, left, right.
The way the box is laid out is determined by:

Box type

Box dimensions

Positioning scheme

External information such as image size and the size of the screen

Box types

Block box: forms a block-has its own rectangle in the browser window.

Inline box: does not have its own block, but is inside a containing block.

Blocks are formatted vertically one after the other. Inlines are formatted horizontally.

Inline boxes are put inside lines or "line boxes". The lines are at least as tall as the tallest box but can be taller, when the boxes are aligned "baseline"-meaning the bottom part of an element is aligned at a point of another box other then the bottom. If the container width is not enough, the inlines will be put on several lines. This is usually what happens in a paragraph.

Positioning

Relative

Relative positioning-positioned like usual and then moved by the required delta.

Floats

A float box is shifted to the left or right of a line. The interesting feature is that the other boxes flow around it The HTML:

<p>
  <img style="float: right" src="images/image.gif" width="100" height="100">
  Lorem ipsum dolor sit amet, consectetuer...
</p>

Will look like:

Absolute and fixed

The layout is defined exactly regardless of the normal flow. The element does not participate in the normal flow. The dimensions are relative to the container. In fixed, the container is the viewport.

Figure : Fixed positioning

Note: the fixed box will not move even when the document is scrolled!

Layered representation

This is specified by the z-index CSS property. It represents the third dimension of the box: its position along the "z axis".

The boxes are divided into stacks (called stacking contexts). In each stack the back elements will be painted first and the forward elements on top, closer to the user. In case of overlap the foremost element will hide the former element.
The stacks are ordered according to the z-index property. Boxes with "z-index" property form a local stack. The viewport has the outer stack.

Example:

<style type="text/css">
      div {
        position: absolute;
        left: 2in;
        top: 2in;
      }
</style>

<p>
    <div
         style="z-index: 3;background-color:red; width: 1in; height: 1in; ">
    </div>
    <div
         style="z-index: 1;background-color:green;width: 2in; height: 2in;">
    </div>
 </p>

The result will be this:

Although the red div precedes the green one in the markup, and would have been painted before in the regular flow, the z-index property is higher, so it is more forward in the stack held by the root box.

Resources

1. Browser architecture

1. Grosskurth, Alan. A Reference Architecture for Web Browsers (pdf)

2. Gupta, Vineet. How Browsers Work-Part 1-Architecture

2. Parsing

1. Aho, Sethi, Ullman, Compilers: Principles, Techniques, and Tools (aka the "Dragon book"), Addison-Wesley, 1986

2. Rick Jelliffe. The Bold and the Beautiful: two new drafts for HTML 5.

3. Firefox

1. L. David Baron, Faster HTML and CSS: Layout Engine Internals for Web Developers.

2. L. David Baron, Faster HTML and CSS: Layout Engine Internals for Web Developers (Google tech talk video)

3. L. David Baron, Mozilla's Layout Engine

4. L. David Baron, Mozilla Style System Documentation

5. Chris Waterson, Notes on HTML Reflow

6. Chris Waterson, Gecko Overview

7. Alexander Larsson, The life of an HTML HTTP request

4. WebKit

1. David Hyatt, Implementing CSS(part 1)

2. David Hyatt, An Overview of WebCore

3. David Hyatt, WebCore Rendering

4. David Hyatt, The FOUC Problem

5. W3C Specifications

1. HTML 4.01 Specification

2. W3C HTML5 Specification

3. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification

6. Browsers build instructions

1. Firefox. https://developer.mozilla.org/en/Build_Documentation

2. WebKit. http://webkit.org/building/build.html

Tali Garsiel is a developer in Israel. She started as a web developer in 2000, and became aquainted with Netscape's "evil" layer model. Just like Richard Feynmann, she had a fascination for figuring out how things work so she began digging into browser internals and documenting what she found. Tali also has published a short guide on client-side performance.

# data[].attributes.attachment_link.title
How Browsers Work: Behind the scenes of modern web browsers - HTML5 Rocks

# data[].attributes.attachment_link.description
Web browsers are the most widely used software. In this primer, I will explain how they work behind the scenes. We will see what happens when you type google.com in the address bar until you see the Google page on the browser screen.

# data[].attributes.attachment_link.readable_text
The human brain is hardwired to pay attention to moving objects. Because of this natural reflex to notice movement, adding animation to your website or app is a powerful way to draw users attention to important areas of your product and add interest to your interface.

When done well, animations can add valuable interaction and feedback, as well as enhance the emotional experience, bring delight, and add personality to your interface. In fact, to animate means to bring to life.

Emotional design's primary goal is to facilitate human-to-human communication. If we're doing our job well, the computer recedes into the background, and personalities rise to the surface.
Aarron Walter, Designing For Emotion

In this post we're going to walk through the basics of CSS animation. You can follow along and view the CSS code for the example animations in this post.

CSS animations are made up of two basic building blocks.

1. Keyframes - define the stages and styles of the animation.

2. Animation Properties - assign the @keyframes to a specific CSS element and definehow it is animated.

Let's look at each individually.

Keyframes are the foundation of CSS animations. They define what the animation looks like at each stage of the animation timeline. Each@keyframes is composed of:

Name of the animation: A name that describes the animation, for example,bounceIn.

Stages of the animation: Each stage of the animation is represented as a percentage.0% represents the beginning state of the animation. 100% represents the ending state of the animation. Multiple intermediate states can be added in between.

CSS Properties: The CSS properties defined for each stage of the animation timeline.

Let's take a look at a simple @keyframes I've named "bounceIn". This@keyframes has three stages. At the first stage (0%), the element is at opacity 0 and scaled down to 10 percent of its default size, using CSS transform scale. At the second stage(60%) the element fades in to full opacity and grows to 120 percent of its default size. At the final stage(100%), it scales down slightly and returns to its default size.

The @keyframes are added to your main CSS file.

(If you're unfamiliar with CSS Transforms, you'll want to brush up on your knowledge. Combining CSS transforms in the animations is really where the magic happens.)

Once the @keyframes are defined, the animation properties must be added in order for your animation to function.

Animation properties do two things:

1. They assign the @keyframes to the elements that you want to animate.

2. They define how it is animated.

The animation properties are added to the CSS selectors (or elements) that you want to animate. You must add the following two animation properties for the animation to take effect:

animation-name: The name of the animation, defined in the @keyframes.

animation-duration: The duration of the animation, in seconds (e.g., 5s) or milliseconds (e.g., 200ms).

Continuing with the above bounceIn example, we'll add animation-name and animation-duration to the div that we want to animate.

Shorthand syntax:

By adding both the @keyframes and the animation properties, we have a simple animation!

Each animation property can be defined individually, but for cleaner and faster code, it's recommended that you use the animation shorthand. All the animation properties are added to the same animation: property in the following order:

Just remember for the animation to function correctly, you need to follow the proper shorthand order AND specify at least the first two values.

As of late 2014, many Webkit based browsers still use the -webkit-prefixed version of both animations, keyframes, and transitions. Until they adopt the standard version, you'll want to include both unprefixed and Webkit versions in your code. (For simplicity, I'll only be using the unprefixed versions in my examples.)

Keyframes and animations with WebKit prefixes:

To make your life easier, consider using Bourbon, a Sass mixin library which contains up-to-date vendor prefixes for all modern browsers. Here's how simple it is to generate vendor-prefixed animations and keyframes using Bourbon:

In addition to the required animation-name and animation-duration properties, you can further customize and create complex animations using the following properties:

Let's look at each of them individually.

The animation-timing-function: defines the speed curve or pace of the animation. You can specify the timing with the following predefined timing options: ease, linear, ease-in, ease-out, ease-in-out, initial, inherit. (Or for more advanced timing options, you can creating custom timing functions using cubic-bezier curve.)

The default value, if no other value is assigned, is ease, which starts out slow, speeds up, then slows down. You can read a description of each timing function here.

CSS syntax:

Animation shorthand syntax (recommended):

The animation-delay: allows you to specify when the animation (or pieces of the animation) will start. A positive value (such as 2s) will start the animation 2 seconds after it is triggered. The element will remain unanimated until that time. A negative value (such as -2s) will start the animation at once, but starts 2 seconds into the animation.

The value is defined in seconds (s) or milliseconds (mil).

CSS syntax:

Animation shorthand syntax (recommended):

The animation-iteration-count: specifies the number of times that the animation will play. The possible values are:

#- a specific number of iterations (default is 1)

infinite - the animation repeats forever

initial - sets the iteration count to the default value

inherit - inherits the value from the parent

CSS syntax:

Animation shorthand syntax (recommended):

The animation-direction: property specifies whether the animation should play forward, reverse, or in alternate cycles.

The possible values are:

normal (default) - The animation plays forward. On each cycle the animation resets to the beginning state (0%) and plays forward again (to 100%).

reverse - The animation plays backwards. On each cycle the animation resets to the end state (100%) and plays backwards (to 0%).

alternate - The animation reverses direction every cycle. On each odd cycle, the animation plays forward (0% to 100%). On each even cycle, the animation plays backwards (100% to 0%).

alternate-reverse - The animation reverses direction every cycle. On each odd cycle, the animation plays in reverse (100% to 0%). On each even cycle, the animation plays forward (0% or 100%).

CSS syntax:

Animation shorthand syntax (recommended):

The animation-fill-mode: specifies if the animation styles are visible before or after the animation plays. This property is a little confusing, but once understood it is very useful.

By default, the animation will not effect the styles of the element before the animation begins (if there is an animation-delay) or after the animation is finished. The animation-fill-mode property can override this behavior with the following possible values:

backwards - Before the animation (during the animation delay), the styles of the initial keyframe (0%) are applied to the element.

forwards - After the animation is finished, the styles defined in the final keyframe (100%) are retained by the element.

both - The animation will follow the rules for both forwards and backwards, extending the animation properties before and after the animation.

normal (default) - The animation does not apply any styles to the element, before or after the animation.

CSS syntax:

Animation shorthand syntax (recommended):

The animation-play-state: specifies whether the animation is playing or paused. Resuming a paused animation starts the animation where it was left off.

The possible values are:

playing - The animation is currently running

paused - The animation is currently paused

Example :

To add multiple animations to a selector, you simply separate the values with a comma. Here's an example:

That's it! With those basic properties, the possible animations you can create are endless. The best way learn is to jump in and start animating.

Here are a couple of resources to get you started:

Upcase for Designers - an online learning community with courses on front-end design and development techniques.

CodePen - a CSS playground where you can edit your code and immediately see your results.

Animate.css - a library with dozens of fun animations to get you started and use on your projects.

# data[].attributes.attachment_link.description
The human brain is hardwired to pay attention to moving objects. Because of this natural reflex to notice movement, adding animation to your website or app is a powerful way to draw users attention to important areas of your product and add interest to your interface.

# data[].attributes.attachment_link.readable_text
What's this post about?

With JavaScript approaching near-ubiquity as the scripting language of the web browser, it benefits you to have a basic understanding of its event-driven interaction model and how it differs from the request-response model typically found in languages like Ruby, Python, and Java. In this post, I'll explain some core concepts of the JavaScript concurrency model, including its event loop and message queue in hopes of improving your understanding of a language you're probably already writing but perhaps don't fully understand.

Who is this post for?

This post is aimed at web developers who are working with (or planning to work with) JavaScript in either the client or the server. If you're already well-versed in event loops then much of this article will be familiar to you. For those of you who aren't, I hope to provide you with a basic understanding such that you can better reason about the code you're reading and writing day-to-day.

Non-blocking I/O

In JavaScript, almost all I/O is non-blocking. This includes HTTP requests, database operations and disk reads and writes; the single thread of execution asks the runtime to perform an operation, providing a callback function and then moves on to do something else. When the operation has been completed, a message is enqueued along with the provided callback function. At some point in the future, the message is dequeued and the callback fired.

While this interaction model may be familiar for developers already accustomed to working with user interfaces - where events like "mousedown," and "click" could be triggered at any time - it's dissimilar to the synchronous, request-response model typically found in server-side applications.

Let's compare two bits of code that make HTTP requests to www.google.com and output the response to console. First, Ruby, with Faraday:

The execution path is easy to follow:

1. The get method is executed and the thread of execution waits until a response is received

2. The response is received from Google and returned to the caller where it's stored in a variable

3. The value of the variable (in this case, our response) is output to the console

4. The value "Done!" is output to the console

Let's do the same in JavaScript with Node.js and the Request library:

A slightly different look, and very different behavior:

1. The request function is executed, passing an anonymous function as a callback to execute when a response is available sometime in the future.

2. "Done!" is immediately output to the console

3. Sometime in the future, the response comes back and our callback is executed, outputting its body to the console

The Event Loop

The decoupling of the caller from the response allows for the JavaScript runtime to do other things while waiting for your asynchronous operation to complete and their callbacks to fire. But where in memory do these callbacks live - and in what order are they executed? What causes them to be called?

JavaScript runtimes contain a message queue which stores a list of messages to be processed and their associated callback functions. These messages are queued in response to external events (such as a mouse being clicked or receiving the response to an HTTP request) given a callback function has been provided. If, for example a user were to click a button and no callback function was provided - no message would have been enqueued.

In a loop, the queue is polled for the next message (each poll referred to as a "tick") and when a message is encountered, the callback for that message is executed.

The calling of this callback function serves as the initial frame in the call stack, and due to JavaScript being single-threaded, further message polling and processing is halted pending the return of all calls on the stack. Subsequent (synchronous) function calls add new call frames to the stack (for example, function init calls function changeColor).

In this example, a message (and callback, changeColor) is enqueued when the user clicks on the 'foo' element and an the "onclick" event fires. When the message is dequeued, its callback function changeColor is called. When changeColor returns (or an error is thrown), the event loop continues. As long as function changeColor exists, specified as the onclick callback for the 'foo' element, subsequent clicks on the element will cause more messages (and associated callback changeColor) to become enqueued.

Queuing Additional Messages

If a function called in your code is asynchronous (like setTimeout), the provided callback will ultimately be executed as part of a different queued message, on some future tick of the event loop. For example:

Due to the non-blocking nature of setTimeout, its callback will fire at least 0 milliseconds in the future and is not processed as part of this message. In this example, setTimeout is invoked, passing a callback function g and a timeout of 0 milliseconds. When the specified time elapses (in this case, almost instantly) a separate message will be enqueued containing g as its callback function. The resulting console activity would look like: "foo", "baz", "blix" and then on the next tick of the event loop: "bar". If in the same call frame two calls are made to setTimeout - passing the same value for a second argument - their callbacks will be queued in the order of invocation.

Web Workers

Using Web Workers enables you to offload an expensive operation to a separate thread of execution, freeing up the main thread to do other things. The worker includes a separate message queue, event loop, and memory space independent from the original thread that instantiated it. Communication between the worker and the main thread is done via message passing, which looks very much like the traditional, evented code-examples we've already seen.

First, our worker:

Then, the main chunk of code that lives in a script-tag in our HTML:

In this example, the main thread spawns a worker and registers the logResult callback function to the its "message" event. In the worker, the reportResult function is registered to its own "message" event. When the worker thread receives the message from the main thread, the worker enqueues a message and corresponding reportResult callback. When dequeued, a message is posted back to the main thread where a new message is enqueued (along with the logResult callback). In this way the developer can delegate CPU-intensive operations to a separate thread, freeing the main thread up to continue processing messages and handling events.

A Note on Closures

JavaScript's support for closures allow you to register callbacks that, when executed, maintain access to the environment in which they were created even though the execution of the callback creates a new call stack entirely. This is particularly of interest knowing that our callbacks are called as part of a different message than the one in which they were created. Consider the following example:

In this example, the changeHeaderDeferred function is executed which includes variable header. The function setTimeout is invoked, which causes a message (plus the changeHeader callback) to be added to the message queue approximately 100 milliseconds in the future. The changeHeaderDeferred function then returns false, ending the processing of the first message - but the header variable is still referenced via a closure and is not garbage collected. When the second message is processed (the changeHeader function) it maintains access to the header variable declared in the outer function's scope. Once the second message (the changeHeader function) is processed, the header variable can be garbage collected.

Takeaways

JavaScript's event-driven interaction model differs from the request-response model many programmers are accustomed to - but as you can see, it's not rocket science. With a simple message queue and event loop, JavaScript enables a developer to build their system around a collection of asynchronously-fired callbacks, freeing the runtime to handle concurrent operations while waiting on external events to happen. However, this is but one approach to concurrency. In the second part of this article I'll compare JavaScript's concurrency model with those found in MRI Ruby (with threads and the GIL), EventMachine (Ruby), and Java (threads).

Additional Reading

# data[].attributes.attachment_link.description
With JavaScript approaching near-ubiquity as the scripting language of the web browser, it benefits you to have a basic understanding of its event-driven interaction model and how it differs from the request-response model typically found in languages like Ruby, Python, and Java.

# data[].attributes.attachment_link.readable_text
If you've done a bit of front-end web development, you're bound to have noticed that not all browsers render all web content in exactly the same way. And neither should they have to: arguably your web content doesn't need to look exactly the same across every browser and device and user might choose to view it on, as long as it still provides a good user experience and gives them access to the content and services required by their current browsing experience.

To get your web content working well on all of the huge, diverse number of different web browsers and web-enabled devices that exist (or even a good proportion of them), you're going to have to do some work, optimizing the layouts and content delivered to each browser, and sometimes even directing certain devices to completely separate web sites. Examples of where such optimization might be required include:

Serving different layouts to narrow screen devices (eg mobile phones) and wide screen devices.

Serving smaller image and video files (or even alternative content representations) to devices that are on a slower internet connection.

Serving cutting edge styling to modern browsers, and alternative styling rules to older browsers that don't support the cutting edge CSS.

There are dozens of techniques available to implement such content, but we don't have space to get anywhere near covering them all in this article. We will provide resources to give you pointers to more information at the end.

This article first focuses on the different mechanisms available to allow us to detect what browser is accessing our content. We'll look at the right and wrong way to do this, and then round it off by showing the different mechanisms available to serve appropriate content to different browsers.

Browser detection is not the way to go!

Ok, so the last paragraph in the introduction is a bit misleading - when you want to serve different content to different browsers, detecting the actual browser type and version itself is the wrong way to go in most cases. It is much better to detect whether the browser supports the technologies your web site is using - referred to as feature detection.

This sounds a bit confusing, so let's investigate further.

A brief history of browser sniffing

These days, a lot of web standards features are supported pretty consistently across browsers, or at least, modern browsers.

We'll touch a bit on older browsers we're still sometimes required to support later in the article. We'll also look later at the fact that really new, cutting edge web standards features (such as parts of CSS3 and HTML5) sometimes don't work the same across modern browsers, and the best way to deal with that.

For now, let's rewind back to the early-to-mid-1990s. Back then, web standards were not supported very consistently at all across browsers, so developers were forced to either only support certain browsers, or fork their code, sending completely different codebases to different browsers. The way this was done back then was browser sniffing, or to be more accurate, UA sniffing.

Every browser has a UA string that you can query to find out what browser it is. This is done in JavaScript using the Navigator object. For example, I'm currently using Opera 12.00 beta. If I run navigator.userAgent in my browser, I get the following returned:

Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; Edition Next; en) Presto/2.10.289 Version/12.00

I can use this to identify the browser as Opera, and then serve code to just Opera as a result.

Back in 1993, NCSA Mosaic was the most popular browser. It was identified by

NCSA_Mosaic/2.0 (Windows 3.1)

This was pretty simple. Then Netscape came along, identified by a UA string of

Mozilla/1.0 (Win3.1)

This was also pretty simple, but here's how the problems started. Netscape supported a new killer web feature of the time, Frames, and Mosaic didn't. So web developers used browser sniffing to detect the browser being used and serve content in frames only to Netscape.

Internet Explorer then came along, and also supported frames, but to make sure it was being served frames, Microsoft used the following UA string to identify itself as Mozilla (compatible):

Mozilla/1.22 (compatible; MSIE 2.0; Windows 95)

This is pretty silly, but things got even sillier. Other browser came along later on, with different rendering engines and names, but they all had to keep the Mozilla string inside their UA string, to make sure they were served good content by all this browser sniffing code. For example:

Mozilla: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.1) Gecko/20020826

Firefox: Mozilla/5.0 (Windows; U; Windows NT 5.1; sv-SE; rv:1.7.5) Gecko/20041108 Firefox/1.0

Opera 9.5: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.51 or Mozilla/5.0 (Windows NT 6.0; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.51 or Opera/9.51 (Windows NT 5.1; U; en)!!!

KHTML: Mozilla/5.0 (compatible; Konqueror/3.2; FreeBSD) (KHTML, like Gecko)

Safari: Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/85.7 (KHTML, like Gecko) Safari/85.5

Chrome: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13

So basically, all these user agent strings are trying to include some kind of identification of the actual browser they belong to and device install on, while strategically trying to be matched by browser sniffing code to make sure the browsers get served decent code.

The problem with browser sniffing

I'm sure you'll agree that the above situation is silly. All of these crazy verbose UA strings have arisen because web developers used short-sighted browser sniffing in the first place, which just sniffed for the first browser to support frames (and later other cool features). When new browsers came out, they had to change their UA strings to work with the browser sniffing code. The other choice would be for developers to keep changing their sniffing code every time a new browser comes out that they want to support. This has happened frequently as well.

and this is the crux of why browser sniffing is so bad - it only solves the problem now, and isn't future proof at all. It is also really error prone. When you are browser sniffing, what you are really want to do is check whether the browser accessing your site supports the technologies your content is built from. But instead of doing this directly, you are making an educated guess dependant on the contents of the UA string, which isn't very precise at all!

For example, you'll notice that the above Opera UA string starts with Opera/9.80, even though at the time of writing we are on version 11.64! This is because of widespread erroneous browsing sniffing code, which looked at Opera UA strings and interpreted Opera 10+ as Opera 1, serving incorrect content as a result.

Why feature detection is better

Feature detection is a much better way to do things - instead of seeing what browser is accessing the content and serving appropriate code, the idea here is to query the browser to detect whether it supports the features our content relies on, and then serve content as appropriate. Let's take HTML5 video as an example. You could detect support using some simple code such as this:

if(!!document.createElement('video').canPlayType === true) {
  // run some code that relies on HTML5 video
} else {
  // do something else
}

This is much more future proof, because existing browsers that support HTML5 video will run the correct code, and future browsers that support HTML5 video will do as well. You don't have to keep updating your code each time a new browser is released.

Strategies for supporting different browsers

Now we've got the argument for feature detection out of the way, let's look at some strategies you can use to serve appropriate content to different browsers.

Graceful degradation

The good news about web technologies is that they are largely designed so that they will work as well as possible if something is not done quite right - this is contrary to other programming environments where nothing will work if there is the slightest error present in the code.

Part of this related to how browsers deal with unknown elements and CSS properties. If a browser encounters an unknown CSS property, it will just ignore it and move on. If a browser encounters an unknown HTML element, it will treat it like an anonymous inline element, similar to a <span>. This means that if a browser is served some HTML or CSS features it can't understand, it will generally just ignore it and move on, rendering the rest of the content. Obviously this might not give you a usable result in all cases, but for text and image content, you'll find that older browsers will render a usable result, even if it doesn't look quite as nice and shiny as in modern browsers. This is generally called graceful degradation.

A quick example:

border-radius and box-shadow aren't supported in older browsers like IE6, but you're still going to be able to read the content inside the box, even if it hasn't got rounded corners and a drop shadow.

[INCLUDE FIGURE TO ILLUSTRATE THIS]

Vendor prefixes, and alternative styles

Of course, you can't rely on graceful degradation in all cases. In some cases, a feature not being supported will result in your content breaking to the point where it is not really usable. In the case of CSS, examples include:

1. Sizing a layout using rem units - these units are not supported in older browsers, resulting in the layout falling apart. To remedy this, you could provide a fallback sized in a unit like pixels later in the cascade, like this:

nav {
  width: 180px;
  width: 18rem;
}

Modern browsers that understand both will first apply the pixel value then override it with the rem value. Older browsers that don't understand rems will just apply the first line, then ignore the second one.

2. Filling in a background using a CSS3 gradient - in browsers that don't support the gradient, it will not render at all, which could cause content to be unreadable.

[INCLUDE FIGURE TO ILLUSTRATE THIS]

To make things better, you could provide a solid background colour as a fallback, or a gradient slice image, like so:

nav {
  background-color: red;
  background-image: url(gradient-slice.png);
  background-image: linear-gradient(top right, #A60000, #FFFFFF);
}

[INCLUDE FIGURE TO ILLUSTRATE THIS]

If you are specifically dealing with fallbacks for old versions of Internet Explorer, you can separate these out into separate stylesheets, and then link to these stylesheets inside an IE conditional comment. For example:

<link rel="stylesheet" href="normal-styles.css" type="text/css" />
<!--[if lte IE 6]>
<link rel="stylesheet"  href="ie-fixes.css" type="text/css" />
<![endif]-->

In this case, the first link element will be given to all browsers, whereas the second one will only be picked up by IE versions 6 and less. In the latter, you could put all your IE fallback styles (such as giving IE6 different width and height values to compensate for its broken box model.)

You can read more about IE conditional comments in Bruce Lawson's article Supporting IE with conditional comments.

Vendor prefixes

Returning to the gradient example we saw earlier, you may have noticed that something wasn't quite right there. To get the gradient rendering across all modern browsers, you need to include multiple versions of the declaration, like this:

nav {
  background-color: red;
  background-image: url(gradient-slice.png);
  background-image: -webkit-linear-gradient(top right, #A60000, #FFFFFF);
  background-image: -moz-linear-gradient(top right, #A60000, #FFFFFF);
  background-image: -ms-linear-gradient(top right, #A60000, #FFFFFF);
  background-image: -o-linear-gradient(top right, #A60000, #FFFFFF);
  background-image: linear-gradient(top right, #A60000, #FFFFFF);
}

This is because the CSS Image Values and Replaced Content Module Level 3 - the spec that CSS gradients are specified in, is not finalised. Unfinished CSS features are implemented in browsers in an experimental capacity, with a vendor-specific prefix so that different browser's implementations can be tested without impacting on other browser's implementations. In the above example:

The -webkit- prefixed property will work in WebKit-based browsers such as Chrome and Safari

The -moz- prefixed property will work in Firefox

The -ms- prefixed property will work in Internet Explorer

The -o- prefixed property will work in Opera

Official W3C policy states that you shouldn't really use experimental properties in production code, but people do, as they want to make sites look cool and keep on the cutting edge. I don't see a problem with this, but if you want to use vendor prefixed properties in your code, you really should use include all the different prefixes so that as many browsers as possible can use all the features you are implementing.

Notice that an unprefixed version of the property has also been included, at the bottom of the list: this is so that when the CSS feature is finalised, and the prefixes are removed, the code will still work - this is good future proofing practice.

Progressive enhancement

The flip side of graceful degradation is progressive enhancement - this goes in the other direction. Instead of building a great experience as the default and then hoping it degrades to something that is still usable in less capable browsers, you build a basic experience that works in all browsers, and then layer an enhanced experience on top of that.

... NEED TO FILL IN AN EXAMPLE?

Polyfills/shims

Another approach you can take to dealing with disparate browser support is using Polyfills/shims. These are bits of utility code (usually JavaScript) that fakes support for a feature you want to use in browsers that don't support that feature natively.

You generally use a polyfill by simply applying the JavaScript to your page via <script src="script.js"></script>, although many of them do have other instructions besides. Always reach the author's instructions carefully before attempting to use one! Polyfill/shim examples include:

respond.js for making Media Queries work in old versions of IE

CSS3PIE for making bling like rounded corners and drop shadows work in old versions of IE

Playr for making HTML5 video <track> work in non-supporting browsers

HTML5 shiv for making old versions of IE render HTML5 semantic elements properly

Excanvas for making Interner Explorer support HTML5 <canvas>

You might think this sounds wonderful! Why worry about what feature different browser support, if you can just fill in support for the ones that don't using JavaScript? The trouble is that using a Polyfill does add weight to a page, both in terms of extra files requiring download, and extra processing required to put the polyfill in action. If you used loads of polyfills on every one of your pages, they would likely be significantly slower to download and run, as well as making your code base a lot more fiddly and complex.

So they are a great idea, but use them sparingly.

Feature detection with Modernizr

You might be thinking at this point "well isn't there a way to only load those extra resources if the browser really needs them?" Well, yes there is. The general idea is to do feature detection to see if the browser supports those features, and then pull in a polyfill or un some alternative code only if needed.

The easiest way to do the feature detection part of this is through a feature detection library called Modernizr. This is a JavaScript library that provides an easy way to do pretty much all of the feature detection you could need. All you have to do is

1. Download the library and attach it to your page via a <script> element.

2. add a class of no-js to your page's <html> element.

When your page runs, Modernizr runs feature tests on all manner of HTML5/CSS3/etc. features, then it does two things. First, it adds classes to your <html> element to allow you to apply CSS to the page selectively, depending on whether the browser supports various feature or not. Second, it provides you with a JavaScript API to allow you to do the same kind of selective code application in your JavaScript. Let's look at these two aspects in more detail.

Selective CSS application

To get things going, you need to link to the Modernizr library and add a class of no-js to the <html> element in your source code. when the page is run, modernizr runs all its feature detection tests and lets you know the results of those tests via a series of classes appended to the <html> element. They will look something like this:

 <html lang="en-gb" class=" js no-flexbox no-flexbox-legacy canvas canvastext webgl no-touch geolocation postmessage websqldatabase no-indexeddb
 hashchange history draganddrop no-websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations
 csscolumns cssgradients no-cssreflections csstransforms no-csstransforms3d csstransitions fontface generatedcontent video audio
 localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths">

This is really powerful, as it allows you to apply CSS to the page selectively, depending whether it supports certain feature or not. For example, if your code uses an animated 3D transform by default to reveal some content underneath:

#shutter:hover {
  transform: rotateX(90deg);
}

You can include alternative styling that overrides this in browsers that don't support 3D transforms like this:

.no-csstransforms3d #shutter:hover {
  position: relative;
  right: 100px;
}

It might not look quite as elegant, but it would still produce an ok experience that allows access to the underlying content.

Selective JavaScript application

Modernizr also provides a nice easy JavaScript API to allow you to execute code selectively, depending on whether CSS/HTML/other features are supported by the browser. Each test is a simple method on the Modernizr object, which returns a boolean (true/false) result. For example, if you wanted to query whether the current browser supports 3D transforms in JavaScript, you would write if(Modernizr.csstransforms3d). So you could have a block of code like this:

if(Modernizr.csstransforms3d) {
  // run killer feature that relies on 3D transforms being available
} else {
  // run an alternative chunk of code that provides a graceful fallback
}

Problems with Modernizr

Modernizr, as with everything, isn't perfect. Two of the main problems are:

1. Not everything can be feature detected and therefore dealt with in this elegant manner.

2. The full Modernizr library weighs in at 49KB, which is quite a lot of extra code to download for a few feature tests.

However, you can customize Modernizr and create a version suitable for your site that only contains the tests you need, which cuts down on the file weight. And even though you can't feature detect everything, you will find it invaluable in many situations.

YepNope - load only what you need!

Now we've covered the feature detection side of things, lets cover what we can do to load resources like Polyfills only when you need them. To help you out with this, Modernizr comes packaged with a really smart, dandy little utility library called YepNope. This can do a lot, but in a nutshell, it allows you to specify a test of some kind, and then say what happens when the test is passed, and when it fails. Here's a simple example:

yepnope({
  test : Modernizr.canvas,
  yep  : 'normal.js',
  nope : ['polyfill.js', 'normal.js']
});

So basically, you are sating what the test is, then saying that if the test is passed, just load the normal script, but if the test fails, load the normal script and a polyfill to allow the code to work in an older browser.

You can find a lot more details on how to use YepNope at The YepNope homepage.

I hope that's helped you get all these ideas clear in your head - why browser sniffing is bad, why feature detection is a much better way to detect whether a browser will run your site features or not, and different strategies for providing different capability browsers with different but acceptable experiences.

If you want to read more sources about the topics discussed above, please check out the following pages:

# data[].attributes.attachment_link.title
Optimizing content for different browsers: the RIGHT way

# data[].attributes.attachment_link.description
If you've done a bit of front-end web development, you're bound to have noticed that not all browsers render all web content in exactly the same way.

# data[].attributes.attachment_link.title
CSS selector , ID selector, Class selector

# data[].attributes.attachment_link.description
The role of a selector is to tell the browser to which style is applied to a specific element in an HTML document ID selector, Class selector

# data[].attributes.attachment_link.description
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

# data[].attributes.attachment_link.title
Code samples for JavaScript & jQuery - a book about interactive front-end web development

# data[].attributes.attachment_link.description
See code samples online and download all source code.

# data[].attributes.attachment_link.readable_text
JavaScript is the world's most popular programming language.

JavaScript is the programming language of the Web.

JavaScript is easy to learn.

This tutorial will teach you JavaScript from basic to advanced.

Start learning JavaScript now "

Examples in Each Chapter

With our "Try it Yourself" editor, you can edit the source code and view the result.

Use the Menu

We recommend reading this tutorial, in the sequence listed in the menu.

If you have a large screen, the menu will always be present on the left.

If you have a small screen, open the menu by clicking the top menu sign ☰.

Learn by Examples

Examples are better than 1000 words. Examples are often easier to understand than text explanations.

This tutorial supplements all explanations with clarifying "Try it Yourself" examples.

If you try all the examples, you will learn a lot about JavaScript, in a very short time!

JavaScript Examples "

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

This tutorial covers every version of JavaScript:

The Original JavaScript ES1 ES2 ES3 (1997-1999)

The First Main Revision ES5 (2009)

The Second Revision ES6 (2015)

The Yearly Additions (2016, 2017 ... 2021, 2022)

Learning Speed

In this tutorial, the learning speed is your choice.

Everything is up to you.

If you are struggling, take a break, or re-read the material.

Always make sure you understand all the "Try-it-Yourself" examples.

The only way to become a clever programmer is to: Practice. Practice. Practice. Code. Code. Code !

Commonly Asked Questions

How do I get JavaScript?

Where can I download JavaScript?

Is JavaScript Free?

You don't have to get or download JavaScript.

JavaScript is already running in your browser on your computer, on your tablet, and on your smart-phone.

JavaScript is free to use for everyone.

My Learning

Track your progress with the free "My Learning" program here at W3Schools.

Log in to your account, and start earning points!

This is an optional feature. You can study at W3Schools without using My Learning.

JavaScript References

W3Schools maintains a complete JavaScript reference, including all HTML and browser objects.

The reference contains examples for all properties, methods and events, and is continuously updated according to the latest web standards.

Complete JavaScript Reference "

JavaScript Quiz Test

Test your JavaScript skills at W3Schools!
Start JavaScript Quiz!
Kickstart your career

Get certified by completing the course

# data[].attributes.attachment_link.description
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

# data[].attributes.body
This lists and uses different selector types as examples

# data[].attributes.attachment_link.description
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

# data[].attributes.attachment_link.description
If you click the save button, your code will be saved, and you get an URL you can share with others.

# data[].attributes.attachment_link.readable_text
Today am gonna explain box-model with the help of CSS background-clip and background-origin property, What is background-clip and background-origin? What are the uses of both of these and what's the difference between each of them. Well, that's a question that runs through the mind of beginner to intermediate level of web developers. Some of them are somewhat familiar with it and other are still wondering where they can actually use these 2 properties.

Well before you can understand these 2 properties, you need to understand CSS box-model. Lets begin with it.

If you create a div and put p into it like this.

<div> <p> some content in here... </p> </div>

and give it some styles.

<style>

</style>

As you can see that we haven't given any padding or border to div element.
So, div element has no padding-box or border-box yet and whole box is considered content-box.

As shown in this image below.

Now, If We give div some padding of 50px from top,bottom,left,right.

Now we have padding-box of 50px & content-box is inside padding-box as shown in this image below.

Now lets remove width from 'p' element so it expands to take the full width of content-box.

You can see the result in image below.

Now, Lets say you add a background image to div and set its background-size to contain to make it adjust its size inside box, Also give it some border cause without border there's no border-box.

div{
 background: #666 url('https://bit.ly/2gzkSPX') no-repeat;
 background-size: contain;
 border: 10px solid black;
 width: 300px;
 height: 250px;
 padding: 50px;
}

Then it will look like this as shown in image below.

By default, div's background-origin is set to padding-box and that means image will start from border-box and will also be visible in content-box cause content-box is inside padding-box.

background-origin: padding-box;  /* default value */

Let's say we want image to start from padding-box but we only want to reveal the portion of image that's inside content-box. Then we need to set div's background-clip to content-box.

div{
 background: #666 url('https://bit.ly/2gzkSPX') no-repeat;
 background-size: contain;
 background-clip: content-box;
 border: 10px solid black;
 width: 300px;
 height: 250px;
 padding: 50px;
}

And you can see the results in image below.

Now, lets also reveal the portion of background image that comes inside padding-box, For that set div's background-clip to padding-box which was the default value before.

div{
 background: #666 url('https://bit.ly/2gzkSPX') no-repeat;
 background-size: contain;
 background-clip: padding-box;
 border: 10px solid black;
 width: 300px;
 height: 250px;
 padding: 50px;
}

You can see the results below.

Now, Lets make sure our div's background image starts from border-box & for that we need to give our div a background-origin of border-box. But first let's increase the size of border to notice the difference.

div{
 background: #666 url('https://bit.ly/2gzkSPX') no-repeat;
 background-size: contain;
 background-origin: border-box;
 background-clip: padding-box;
 border: 20px solid black; /* Its 20px now */
 width: 300px;
 height: 250px;
 padding: 50px;
}

Now you can see in the image below that because background image is starting from border-box that's why a small portion of image is covered by black border because the small portion of image is behind the border.

Now to prove my point that image is starting from border-box and that's why small portion of image is covered with black border. Let's give border some opacity so that it can fadeout and we can see the image behind that border.

div{
 background: #666 url('https://bit.ly/2gzkSPX') no-repeat;
 background-size: contain;
 background-origin: border-box;
 background-clip: padding-box;
 border: 20px solid rgba(0,0,0,0.5); /* using rgba() */
 width: 300px;
 height: 250px;
 padding: 50px;
}

Here you go! I hope everything makes sense now. Now that you know what's the difference between background-origin & background-clip + you also know about CSS box-model now, Its time for you to go get build some amazing stuffs with it. :)

If you missed my previous article about web accessibility then here's the link to it, Don't forget to read it to learn some cool stuffs. CLICK HERE

# data[].attributes.attachment_link.title
CSS box-model explained with example. - Usama Tahir - Medium

# data[].attributes.attachment_link.description
Today am gonna explain box-model with the help of CSS background-clip and background-origin property, What is background-clip and background-origin? What are the uses of both of these and what's the difference between each of them. Well, that's a question that runs through the mind of beginner to intermediate level of web developers.

# data[].attributes.attachment_link.readable_text
What is the Box Model?
The box model is a tool we use to understand how our content will be displayed on a web page.

Each XHTML element appearing on our page takes up a "box" or "container" of space.

Each box size is affected not only by content but also by padding, borders, and margins.

By knowing how to calculate the dimensions of each box, we can accurately predict how elements will lay out on the screen.

As we build a new page, we can arrange these boxes on the screen, creating a balanced layout with white space around the content.

Box Model Components
This model describes the content of the space taken by an element. Each element has four components: the margin, border, padding, and content.

Content
The content area is the area containing the real content of the element. It often has a background, a color or an image and is located inside the content edge; its dimensions are the content width, or content-box width, and the content height, or content-box height.

Padding
The padding area is the space between the content of the element and its border. Negative values are not allowed. The padding clears an area around the content (inside the border) of an element. This property sets the padding space on all sides of an element.

The border area extends the padding area to the area containing the borders. It is the area inside the border edge, and its dimensions are the border-box width and the border-box height. This area depends on the size of the border that is defined by the border-width property or the shorthand border.

Margin
The margin property defines the outermost portion of the box model, creating space around an element, outside of any defined borders.

The <div> Element
The<div> tag defines a division or a section in an HTML document. The <div> tag is used to group block-elements to format them with CSS.

The <div> ("division") element groups other elements on the screen.

By setting the width and height attributes via CSS, we can reserve a precise amount of space on our page for specific content.

The actual content is nested and contained within the opening

When we apply CSS styling directly to the <div> element, all the elements contained within that <div> will inherit that style.

By using multiple <div> elements as building blocks, we can design an entire web page layout.

Example <div> Element
Let's create a box on the screen and add a border around it:
Notice that there is almost no space separating the text from the box border. Elements such as paragraphs, headers, and lists automatically insert padding and margins, but plain text does not do so.

Adding Padding and Margin
Let's create some space between elements by adding both padding and margin:

The 10 pixel padding adds buffer space, on all four sides, between the content and border. The 10 pixel margin adds buffer space, on all four sides, between the border and surrounding elements.

Padding and Margin Illustrated

When we define the width and height of a <div> element, these dimensions apply only to the actual content, not to the padding, border, or margin.

Calculating Total Dimensions
When we are planning our page, we have to calculate exactly how much screen space a <div> or any other element will use. The formula is:

Total element width = defined width + left padding + right padding + left border + right border + left margin + right margin.

Total element height = defined height + top padding + bottom padding + top border + bottom border + top margin + bottom margin.

In our previous example:

Total <div> width = 200px + 10px + 10px + 1px + 1px + 10px + 10px = 242px.

Total <div> height = 200px + 10px + 10px + 1px + 1px + 10px + 10px = 242px.

Padding, borders, and margins do not have to be the same on all four sides, as they are in this example.
Setting Individual Margins
We can set the specific margin sizes by using these four properties:
In practice, few web designers use these properties, preferring a shorthand method that condenses the declaration to a single line:

Setting Individual Padding
We can set specific padding sizes by using these four properties:

The same shorthand method is employed:

Setting Individual Borders
To make things easier, we can use the shorthand method as before:
If the three border properties will be identical on all four sides, we can use a single-line border shorthand, as we did in an earlier lesson:

Example of Customized Settings
Here we have set custom padding, borders, and margins:

# data[].attributes.attachment_link.description
What is the Box Model? The box model is a tool we use to understand how our content will be displayed on a web page. Each XHTML element appearing on our page takes up a "box" or "container" of space. Each box size is affected not only by content but also by padding, borders, and...

# data[].attributes.attachment_link.readable_text
You've probably heard that JavaScript is dangerous. Well, that's partly correct. JavaScript can be dangerous if the proper precautions aren't taken. It can be used to view or steal personal data without you even realizing that it's happening. And since JavaScript is so ubiquitous across the web, we're all vulnerable.

The Benefits Of JavaScript

First things first, JavaScript is a good thing. According to W3Techs, approximately 88.1% of all websites use JavaScript in one way or another. Most of the big name sites - such as Amazon and YouTube - would be nowhere near as useful if the Internet was a JavaScript-free zone.

For example, JQuery is a popular JavaScript library that makes it easy to create interactive websites with elements that can change without having to reload the entire page. Sites like Facebook and Twitter rely on technologies like AJAX to keep webpages up to date (e.g. timestamps, # of Likes, etc.) without refreshing the page every second.

But as we'll soon see, JavaScript is not perfect. It can be abused, and that abuse leads to scenarios that make it possible to snoop on your Internet activity and violate your privacy.

One common yet misguided piece of advice is to disable JavaScript entirely but we don't recommend it. You'd lose out on a lot of awesome web functionality, such as the "infinite scrolling" feature that exists on many blogs, social networks, and news sites.

But more so, some browser exploits are still possible even if you disable JavaScript. Thus, disabling JavaScript due of security concerns is like wearing a bubble suit every time you go outside because you're afraid of getting hurt. It won't actually protect you from much, but it will make your life miserable.

Snooping The Words You Type

In July 2012, a pair of researchers sampled data from 5 million Facebook users in America and the United Kingdom. What were they looking for? Self-censorship. More specifically, they wanted to know how often users would start writing a post but end up deleting it before it was actually posted.

They did this by embedding a bit of JavaScript that tracked the textboxes where users could make status updates, write wall comments, etc. The researchers made it clear that they only recorded "the presence or absence of text entered" rather than "keystrokes or content," but the implication is clear.

It was possible to track keystrokes and content. They just chose not to.

The notion is a scary one. A simple chunk of embedded JavaScript is all that's needed to record any kind of activity on a webpage - even if you don't actually submit anything! Web scrolling, mouse movements, keystrokes: all of it can be tracked and recorded against your will or knowledge.

Tracking Your Browsing Habits

Cookies are persistent, meaning they continue to exist even after you leave the webpage or close your browser (unless they expire or you delete them manually). Do you see the growing problem? If a cookie persists from webpage to webpage, it's possible for a company to see which websites you visit.

This is best explained with an example: social share buttons. Consider the Facebook Like button, which uses JavaScript to perform its action. When your browser loads the page, it has to load the button. Loading the button means making a request to Facebook for the necessary JavaScript file. That request includes data like your IP address, the webpage you're on, any Facebook cookies on your system, etc.

Just to be clear, you don't need to click the button for it to track you. The act of loading is enough for these share widgets to gather data on you.

That being said, social share buttons are just one of many ways companies can track your browsing habits. Other examples include online dating profiles, Disqus comments, and websites that use Google's free web fonts.

Malicious Code Injection

One of the most insidious uses of JavaScript occurs in the form of cross-site scripting (XSS). Simply put, XSS is a vulnerability that allows hackers to embed malicious JavaScript code into an otherwise legitimate website, which is ultimately executed in the browser of a user who visits the site.

And then there's something called a cross-site request forgery (CSRF), which is the inverse of an XSS. This kind of malicious JavaScript code can exploit a user's browser, cookies, and security permissions in order to perform actions on a separate website.

What Can You Do To Protect Against JavaScript-Based Attacks?

That being said, I can count on one hand the number of times I've run into the above problems. JavaScript is an important part of the modern web. It has done more good for us than bad and it's here to stay. Interested in becoming a JavaScript developer? Get started with these free learning resources.
Have you ever run into any JavaScript problems? Are you practicing safe habits for security and privacy? Tell us about your experiences in the comments below! Image Credits: Facebook Notifications Via Shutterstock, Typing Hands Via Shutterstock, Social Share Buttons Via Shutterstock

# data[].attributes.attachment_link.title
3 Ways JavaScript Can Breach Your Privacy & Security

# data[].attributes.attachment_link.description
You've probably heard that JavaScript is dangerous. Well, that's partly correct. JavaScript can be dangerous if the proper precautions aren't taken. It can be used to view or steal personal data without you even realizing that it's happening. And since JavaScript is so ubiquitous across the web, we're all vulnerable.

# data[].attributes.headline
Clear steps explaining all we have covered from week 1 to week 6

# data[].attributes.subject
Clear steps explaining all we have covered from week 1 to week 6

# data[].attributes.attachment_link.readable_text
In web development, we use Cascading Style Sheets (CSS) to describe the presentation of a HTML document (i.e. its look and feel).

Each element within a HTML document can be styled. The CSS for a given HTML element describes how it is to be rendered on screen. This is done by ascribing values to the different properties associated with an element. For example, the property could be set to to make any text contained within the specified HTML element to appear at 24pt. We could also set the property to a value of to make text appear within the HTML element on the right-hand side.

Note

There are many, many different CSS properties that you can use in your stylesheets. Each provides a different functionality. Check out the W3C website and HTML Dog for lists of available properties. pageresource.com also has a neat list of properties, with descriptions of what each one does. Check out Section 19.12 for a more comprehensive set of links.

CSS works by following a select and apply pattern - for a specified element, a set of styling properties are applied. Take a look at the following example in Figure 1 where we have some HTML containing tags. In the CSS code example, we specify that all are styled. We'll come back to selectors in Section 19.2. For now though, you can assume the CSS style defined will be applied to our tags. The style contains four properties:

the first property () sets the size of the font to 16pt;

the second property () italicises the contents of all tags within the document;

the third property () centres the text of the tags; and

the final property () sets the colour of the text to red via hexadecimal code .

With all of these properties applied, the resultant page render can be seen in the browser in Figure 1.

Note

Due to the nature of web development, what you see isn't necessarily what you'll get. This is because different browsers have their own way of interpreting web standards and so the pages may be rendered differently. This quirk can unfortunately lead to plenty of frustration.

19.1. Including Stylesheets

Including stylesheets in your webpages is a relatively straightforward process, and involves including a tag within your HTML's . Check out the minimal HTML markup sample below for the attributes required within a tag.

As can be seen from above, there are at minimum three attributes which you must supply to the tag:

, which allows you to specify the relationship between the HTML document and the resource you're linking to (i.e., a stylesheet);

, in which you should specify the MIME type for CSS; and

, the attribute which you should point to the URL of the stylesheet you wish to include.

With this tag added, your stylesheet should in included with your HTML page, and the styles within the stylesheet applied. It should be noted that CSS stylesheets are considered by Django as static media, meaning you should place them within your project's directory.

Note

You can also add CSS to your HTML documents inline, meaning that the CSS is included as part of your HTML page. However, this isn't generally advised because it removes the nice abstraction between presentational semantics (CSS) and content (HTML).

19.2. Basic CSS Selectors

CSS selectors are used to map particular styles to particular HTML elements. In essence, a CSS selector is a pattern. Here, we cover three basic forms of CSS selector: element selectors, id selectors and class selectors. In Section 19.10, we also touch on what are known as pseudo-selectors.

19.3. Element Selectors

Taking the CSS example from Figure 1, we can see that the selector matches to any tag. Any selector referencing a tag like this can be called an element selector. We can apply element selectors to any HTML element such as , , , , and . These can be all styled in a similar manner. However, using element selectors is pretty crude - styles are applied to all instances of a particular tag. We usually want a more fine-grained approach to selecting what elements we style, and this is where id selectors and class selectors come into play.

19.3.1. ID Selectors

The id selector is used to map to a unique element on your webpage. Each element on your webpage can be assigned a unique id via the attribute, and it is this identifier that CSS uses to latch styles onto your element. This type of selector begins with a hash symbol (), followed directly by the identifier of the element you wish to match to. Check out Figure 2 for an example.

19.3.2. Class Selectors

The alternative option is to use class selectors. This approach is similar to that of id selectors, with the difference that you can legitimately target multiple elements with the same class. If you have a group of HTML elements that you wish to apply the same style to, use a class-based approach. The selector for using this method is to precede the name of your class with a period () before opening up the style with curly braces (). Check out Figure 3 for an example.

Warning

19.4. Fonts

Due to the huge number available, using fonts has historically been a pitfall when it comes to web development. Picture this scenario: a web developer has installed and uses a particular font on his or her webpage. The font is pretty arcane - so the probability of the font being present on other computers is relatively small. A user who visits the developer's webpage subsequently sees the page rendered incorrectly as the font is not present on their system. CSS tackles this particular issue with the font-family property.

The value you specify for font-family can be a list of possible fonts - and the first one your computer or other device has installed is the font that is used to render the webpage. Text within the specified HTML element subsequently has the selected font applied. The example CSS shown below applies Arial if the font exists. If it doesn't, it looks for Helvetica. If that font doesn't exist, any available sans-serif font is applied.

In 1996, Microsoft started the Core fonts for the Web initiative with the aim of guaranteeing a particular set of fonts to be present on all computers. Today however, you can use pretty much any font you like - check out Google Fonts for examples of the typesets you can use and this Web Designer Depot article on how to use such fonts.

19.5. Colours and Backgrounds

Colours are important in defining the look and feel of your website. You can change the colour of any element within your webpage, ranging from background colours to borders and text. In this book, we make use of words and hexadecimal colour codes to choose the colours we want. As you can see from the list of basic colours in Figure 4, you can supply either a hexadecimal or RGB (red-green-blue) value for the colour you want to use. You can also specify words to describe your colours, such as , or .

Warning

You must take great care when picking colours to use on your webpages. Don't select colours that don't contrast well - people simply won't be able to read them! There are many websites available that can help you pick out a good colour scheme - try colorcombos.com for starters.

Applying colours to your elements is a straightforward process. The property that you use depends on the aspect of the element you wish to change! The following subsections explain the relevant properties and how to apply them.

There are many different websites which you can use to aid you in picking the right hexadecimal codes to enter into your stylesheets. You aren't simply limited to the nine examples above! Try out html-color-codes.com for a simple grid of colours and their associated six character hexadecimal code. You can also try sites such as color-hex.com which gives you fine-grain control over the colours you can choose.

Warning

As you may have noticed, CSS uses American/International English to spell words. As such, there are a few words which are spelt slightly differently compared to their British counterparts, like and . If you have grown up in Great Britain, double check your spelling and be prepared to spell it the wrong way! Hah!

19.5.1. Text Colours

To change the colour of text within an element, you must apply the property to the element containing the text you wish to change. The following CSS for example changes all the text within an element using class to...red!

19.5.2. Borders

You can change the colour of an element's borders, too. We'll discuss what borders are in Section 19.8 - but for now, we'll show you how to apply colours to them to make everything look pretty.

Border colours can be specified with the border-color property. You can supply one colour for all four sides of your border, or specify a different colour for each side. To achieve this, you'll need to supply different colours, each separated by a space.

In the example above, we use multiple colours to specify a different colour for three sides. Starting at the top, we rotate clockwise. Thus, the order of colours for each side would be .

Our example applies any element with class some-element with a black top border, a red right border and a green bottom border. No left border value is supplied, meaning that the left-hand border is left transparent. To specify a color for only one side of an element's border, consider using the border-top-color , border-right-color , border-bottom-color and border-left-color properties where appropriate.

19.5.3. Background Colours

19.5.4. Background Images

Of course, a colour isn't the only way to change your backgrounds. You can also apply background images to your elements, too. We can achieve this through the background-image property.

The example above makes use of filename.png as the background image for the element with identifier some-unique-element . The path to your image is specified relative to the path of your CSS stylesheet. Our example above uses the double dot notation to specify the relative path to the image. Don't provide an absolute path here; it won't work as you expect! We also apply a black background colour to fill the gaps left by our background image - it may not fill the entire size of the element.

Note

19.6. Containers, Block-Level and Inline Elements

Throughout the crash course thus far, we've introduced you to the element but have neglected to tell you what it is. All will become clear in this section as we explain inline and block-level elements.

A is considered to be a so-called container element. Along with a tag, these elements are themselves meaningless and are provided only for you to contain and separate your page's content in a logical manner. For example, you may use a to contain markup related to a navigation bar, with another to contain markup related to the footer of your webpage. As containers themselves are meaningless, styles are usually applied to help control the presentational semantics of your webpage.

Containers come in two flavours: block-level elements and inline elements. Check out Figure 5 for an illustration of the two kinds in action, and read on for a short description of each.

19.6.1. Block-Level Elements

In simple terms, a block-level element are by default rectangular in shape and spread across the entire width of the containing element. Block-level elements therefore by default appear underneath each other. The rectangular structure of each block-level element is commonly referred to as the box model, which we discuss in Section 19.8. A typical block-level element you will use is the tag, short for division.

Block-level elements can be nested within other block-level elements to create a hierarchy of elements. You can also nest inline elements within block-level elements, but not vice-versa! Read on to find out why.

19.6.2. Inline Elements

An inline element does exactly what it says on the tin. These elements appear inline to block-level elements on your webpage, and are commonly found to be wrapped around text. You'll find that tags are commonly used for this purpose.

This text-wrapping application was explained in Section 19.5.1, where a portion of text could be wrapped in tags to change its colour. The corresponding HTML markup would look similar to the example below.

Refer back to Figure 5 to refresh your mind about what you can and cannot nest before you move on.

19.7. Basic Positioning

An important concept that we have not yet covered in this CSS crash course regards the positioning of elements within your webpage. Most of the time, you'll be satisfied with inline elements appearing alongside each other, and block-level elements appearing underneath each other. These elements are said to be positioned statically.

However, there will be scenarios where you require a little bit more control on where everything goes. In this section, we'll briefly cover three important techniques for positioning elements within your webpage: floats, relative positioning and absolute positioning.

19.7.1. Floats

CSS floats are one of the most straightforward techniques for positioning elements within your webpage. Using floats allows us to position elements to the left or right of a particular container - or page.

Let's work through an example. Consider the following HTML markup and CSS code.

This produces the output shown below.

We can see that each element follows its natural flow: the container element with class spans the entire width of its parent container, while each of the elements are enclosed inline within the parent. Now suppose that we wish to then move the blue element with text to the right of its container. We can achieve this by modifying our CSS class to look like the following example.

By applying the property and value pairing, we should then see something similar to the example shown below.

Note how the element now appears at the right of its parent container, . We have in effect disturbed the natural flow of our webpage by artificially moving an element! What if we then also applied to the ?

This would float the element, removing it from the natural flow of the webpage. In effect, it is not sitting on top of the container. This explains why the parent container does not now fill down with the elements like you would expect. You can apply the property to the parent container as shown below to fix this problem. For more information on how this trick works, have a look at this QuirksMode.org online article.

Applying ensures that that our pushes down to the appropriate height.

19.7.2. Relative Positioning

Relative positioning can be used if you required a greater degree of control over where elements are positioned on your webpage. As the name may suggest to you, relative positioning allows you to position an element relative to where it would otherwise be located. We make use of relative positioning with the property and value pairing. However, that's only part of the story.

Let's explain how this works. Consider our previous example where two elements are sitting within their container.

This produces the following result - just as we would expect. Note that we have artificially increased the of our element to 150 pixels. This will allow us more room with which to play with.

Now let's attempt to position our element relatively. First, we apply the property and value pairing to our class, like so.

This has no effect on the positioning of our element. What it does do however is change the positioning of from to . This paves the way for us to specify where - from the original position of our element - we now wish the element to be located at.

By applying the and properties as shown in the example above, we are wanting the element to be pushed 150 pixels from the left. In other words, we move the element 150 pixels to the right. Think about that carefully! The property indicates that the element should be pushed 80 pixels from the top of the element. The result our experimentation can be seen below.

From this behaviour, we can deduce that the properties and push elements from the right and bottom respectively. We can test this out by applying the properties to our class as shown below.

This produces the following output. The container is pushed into the top left-hand corner of our container by pushing up and to the right.

Note

We can even apply relative positioning to elements which are floated. Consider our earlier example where the two elements were positioned on either side of the container by floating to the right.

We can then alter the class to the following.

This therefore means that relative positioning works from the position at which the element would have otherwise been at - regardless of any other position-changing properties being applied. Neat!

19.7.3. Absolute Positioning

Our final positioning technique is absolute positioning. While we still modify the parameter of a style, we use as the value instead of . In contrast to relative positioning, absolute positioning places an element relative to its first parent element that has a position value other than static. This may sound a little bit confusing, but let's go through it step by step to figure out what exactly happens.

This produces the output shown below. Note that we again set our height to an artificial value of 70 pixels to give us more room.

We now apply absolute positioning to our element.

Like with relative positioning, this has no overall effect on the positioning of our blue element in the webpage. We must apply one or more of , , or in order for a new position to take effect. As a demonstration, we can apply and properties to our blue element like in the example below.

Wow, what happened here? Our blue element is now positioned outside of our container! You'll note that if you run this code within your own web browser window, the blue element appears in the top left-hand corner of the viewport. This therefore means that our , , and properties take on a slightly different meaning when absolute positioning is concerned.

As our container element's position is by default set to , the blue and yellow elements are moving to the top left and bottom right of our screen respectively. Let's now modify our class to move the yellow to 5 pixels from the bottom right-hand corner of our page. The class now looks like the example below.

This produces the following result.

But what if we don't want our elements to be positioned absolutely in relation to the entire page? More often than not, we'll be looking to adjusting the positioning of our elements in relation to a container. If we recall our definition for absolute positioning, we will note that absolute positions are calculated relative to the first parent element that has a position value other than static. As our container is the only parent for our two elements, the container to which the absolutely positioned elements is therefore the of our HTML page. We can fix this by adding to our class, just like in the example below.

Our elements are now absolutely positioned in relation to . Awesome! Let's adjust the positioning values of our two elements to move them around.

Note that we also apply to our element. This is to demonstrate that unlike relative positioning, absolute positioning ignores any other positioning properties applied to an element. for example will always ensure that an element appears 10 pixels down from its parent (set with ), regardless of whether the element has been floated or not.

19.8. The Box Model

When using CSS, you're never too far away from using padding, borders and margins. These properties are some of the most fundamental styling techniques which you can apply to the elements within your webpages. They are incredibly important and are all related to what we call the CSS box model.

Each element that you create on a webpage can be considered as a box. The CSS box model is defined by the W3C as a formal means of describing the elements or boxes that you create, and how they are rendered in your web browser's viewport. Each element or box consists of four separate areas, all of which are illustrated in Figure 6. The areas - listed from inside to outside - are the content area, the padding area, the border area and the margin area.

For each element within a webpage, you can create a margin, apply some padding or a border with the respective properties , and . Margins clear a transparent area around the border of your element, meaning margins are incredibly useful for creating a gap between elements. In contrast, padding creates a gap between the content of an element and its border. This therefore gives the impression that the element appears wider. If you supply a background colour for an element, the background colour is extended with the element's padding. Finally, borders are what you might expect them to be - they provide a border around your element's content and padding.

For more information on the CSS box model, check out addedbytes excellent explanation of the model. Heck, why not even order a t-shirt with the box model on it?

Warning

As you may gather from examining Figure 6, the width of an element isn't defined simply by the value you enter as the element's . Rather, you should always consider the width of the border and padding on both sides of your element. This can be represented mathematically as:

Don't forget this. You'll save yourself a lot of trouble if you don't!

19.9. Styling Lists

Lists are everywhere. Whether you're reading a list of learning outcomes for a course or a reading a list of times for the train, you know what a list looks like and appreciate its simplicity. If you have a list of items on a webpage, why not use a HTML list? Using lists within your webpages - according to Brainstorm and Raves - promotes good HTML document structure, allowing text-based browsers, screen readers and other browsers that do not support CSS to render your page in a sensible manner.

Lists however don't look particularly appealing to end-users. Take the following HTML list that we'll be styling as we go along trying out different things.

Rendered without styling, the list looks pretty boring.

Django

How to Tango with Django

Two Scoops of Django

Let's make some modifications. First, let's get rid of the ugly bullet points. With our element already (and conveniently) set with class sample-list , we can create the following style.

This produces the following result. Note the now lacking bullet points!

Django

How to Tango with Django

Two Scoops of Django

Let's now change the orientation of our list. We can do this by altering the property of each of our list's elements (). The following style maps to this for us.

When applied, our list elements now appear on a single line, just like in the example below.

While we may have the correct orientation, our list now looks awful. Where does one element start and the other end? It's a complete mess! Let's adjust our list element style and add some contrast and padding to make things look nicer.

When applied, our list looks so much better - and quite professional, too!

From the example, it is hopefully clear that lists can be easily customised to suit the requirements of your webpages. For more information and inspiration on how to style lists, you can check out some of the selected links below.

The possibilities of styling lists is endless! You could say it's a never-ending list...

19.11. The Cascade

It's worth pointing out where the Cascading in Cascading Style Sheets comes into play. You may have noticed in the example rendered output in Figure 1 that the red text is bold, yet no such property is defined in our style. This is a perfect example of what we mean by cascading styles. Most HTML elements have associated with them a default style which web browsers apply. For elements, the W3C website provides a typical style that is applied. If you check the typical style, you'll notice that it contains a property and value pairing, explaining where the bold text comes from. As we define a further style for elements, typical property/value pairings cascade down into our style. If we define a new value for an existing property/value pairing (such as we do for ), we override the existing value. This process can be repeated many times - and the property/value pairings at the end of the process are applied to the relevant element. Check out 7 for a graphical representation of the cascading process.

19.12. Additional Reading

What we've discussed in this section is by no means a definitive guide to CSS. There are 300-page books devoted to CSS alone! What we have provided you with here is a very brief introduction showing you the very basics of what CSS is and how you can use it.

As you develop your web applications, you'll undoubtedly run into issues and frustrating problems with styling web content. This is part of the learning experience, and you still have a bit to learn. We strongly recommend that you invest some time trying out several online tutorials about CSS - there isn't really any need to buy a book (unless you want to).

The W3C provides a neat tutorial on CSS, taking you by the hand and guiding you through the different stages required. They also introduce you to several new HTML elements along the way, and show you how to style them accordingly.

W3Schools also provides some cool CSS tutorials. Instead of guiding you through the process of creating a webpage with CSS, W3Schools has a series of mini-tutorials and code examples to show you to to achieve a particular feature, such as setting a background image. We highly recommend that you have a look here.

html.net has a series of lessons on CSS which you can work through. Like W3Schools, the tutorials on html.net are split into different parts, allowing you to jump into a particular part you may be stuck with.

It's also worth having a look at CSSeasy.com's collection of tutorials, providing you with the basics on how to develop different kinds of page layouts.

This list is by no means exhaustive, and a quick web search will indeed yield much more about CSS for you to chew on. Just remember: CSS can be tricky to learn, and there may be times where you feel you want to throw your computer through the window. We say this is pretty normal - but take a break if you get to that stage. We'll be tackling some more advanced CSS stuff as we progress through the tutorial in the next few sections.

Note

With an increasing array of devices equipped with more and more powerful processors, we can make our web-based content do more. To keep up, CSS has constantly evolved to provide new and intuitive ways to express the presentational semantics of our SGML-based markup. To this end, support for relatively new CSS properties may be limited on several browsers, which can be a source of frustration. The only way to reliably ensure that your website works across a wide range of different browsers and platforms is to test, test and test some more!

# data[].attributes.attachment_link.title
19. A CSS Crash Course - How to Tango with Django 1.5.4

# data[].attributes.attachment_link.description
In web development, we use Cascading Style Sheets (CSS) to describe the presentation of a HTML document (i.e. its look and feel). Each element within a HTML document can be styled. The CSS for a given HTML element describes how it is to be rendered on screen.

# data[].attributes.attachment_link.readable_text
You know you should use JavaScript when the task cannot be accomplished with any other technology.

That's what Doug suggested when I asked him for a nicer spin on a something that was going through my head:

JavaScript: If it can be done in another language, it should be done in another language.

That just sounds so negative, which is definitely not what I'm getting at here. But I am trying to make a point. JavaScript is capable of doing taks that can also be accomplished in other languages. JavaScript is also capable of doing things that cannot be done in any other language. Some examples are probably in order.

Form Validation

You can validate a form with JavaScript. You can create a great user experience doing it this way, but of coures you'd be dumb not to validate all the inputs again with a server side language before processing them. If you are going to pick one or the other, go server side. If it can be done with another language, use the other language.

Inserting Content

I just had a circumstance where I needed to load in a block of dynamic navigation onto the homepage of a site that was created by a CMS in a subdirectory of the site. Ideally, this navigation would be created in a file that could be server-side-included on the homepage and anywhere else that needed it. Long story short, I couldn't make it happen. Instead, I used jQuery load function to grab the block. Works great, unless you don't/can't use JavaScript. If it can be done with another language, use the other language.

In a similar vein, the whole concept of AJAX is generally regarded as a hack. It is a way to simulate two-way communication in a technology built for one-way delivery. When something new comes along that more naturally accommodates two way browser-server communication, AJAX is gone. If it can be done with another language, use the other language.

Styling

JavaScript is capable of applying styling to elements on the page. That's also the job of CSS. Having a bunch of styling information in the JavaScript muddies the water. It makes the JavaScript harder to read, and styling updates more difficult to track down. If it can be done with another language, use the other language.

One of the major reasons JavaScript libraries are popular is because they open up some awesome design possibilities. You can fade things in and out, animate sizes and positions, and do it with smoothness and style. But these things are design related, not (usually) functionality related. Hence, we are seeing CSS starting to accommodate doing these same exact things. I would argue CSS is the appropriate place for this, rather than the somewhat hacky "rapidly altering the DOM" technique JavaScript libraries use. If it can be done with another language, use the other language.

When TO Use

Alright enough don't-use cases. There are many more circumstances where using JavaScript is the only option. How about events? JavaScript is the only language available for having your website communicate with the browser and watch for events: clicks, double clicks, mouse enters, mouse exits, key presses, browser window sizing... the list goes on. If you need access to those events, you are in JavaScript territory.

Am I right? Is this narrow minded thinking?

# data[].attributes.attachment_link.title
You Know You Should Use JavaScript When... | CSS-Tricks

# data[].attributes.attachment_link.description
You know you should use JavaScript when the task cannot be accomplished with any other technology. That's what Doug suggested when I asked him for a nicer spin on a something that was going through my head: JavaScript: If it can be done in another language, it should be done in another language.

# data[].attributes.attachment_link.description
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, and XML.

# data[].attributes.attachment_link.description
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, and XML.

# data[].attributes.attachment_link.description
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, and XML.

# data[].attributes.attachment_link.description
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, and XML.

# data[].attributes.attachment_link.description
A typical major browser has a graphical engine and an independent JavaScript engine, which allows for easier testing, reimplementation or use in other projects. For example, Carakan is used with Presto; Nitro with WebKit; SpiderMonkey with Gecko; KJS with KHTML; Rhino by default has no layout engine.

# data[].attributes.headline
Why does javascript run differntly from browser to browser

# data[].attributes.subject
Why does javascript run differntly from browser to browser

# data[].attributes.attachment_link.readable_text
The short answer is every browser writes it's own interpreter for JS
The long answer
To understand why a programming language functions differently you have to understand what happens to a programming language at execution. First there are two types of languages interpreted and compiled. Compiled languages are turned from people readable "code" to machine code before execution and distributed as a binary.

Interpreted languages are compiled on the fly, JS is one of those languages. What does it mean to compile a language on the fly? Well, a computer can understand nothing but 1's and 0's and because of this all higher level languages must be broken down to instructions and then binary. When something is compiled on the fly it compiles a line, then runs it, then compiles the next. (of course there are intricacies but that really is the short of it)

Because JS really has never had a stand alone interpreter until recently, and the browser is JS's main purpose every company had to write their own interpreter that would go into their browser. Microsoft, Mozilla, Netscape... Everyone needed to think of how certain things could be handled and then execute them.

Because of this two things happen first, you are never gonna get the same thing if two people are working on it. Think about when you take an intro to Comp Sci course everyone has to make a calculator app but everyone takes a different approach. That happens all the time with js, and causes some browsers to crawl while others fly.

The second is that companies get set in their ways, they have too much time and energy invested in their interpreter and don't want to start over when modifying works and is cheaper. This means that differences that arose in the past when JS was less used and no where near as critical to web development will remain just because it's really difficult to roll out a whole new version of IE with webkit when it has been centered around it's own interpreter for years.

# data[].attributes.attachment_link.title
How is it that Javascript can function differently from browser to browser?

# data[].attributes.attachment_link.description
The short answer is every browser writes it's own interpreter for JS The long answer To understand why a programming language functions differently you have to understand what happens to a programming language at execution. First there are two types of languages interpreted and compiled.

# data[].attributes.body
Lies, Damned lies and statistics....

# data[].attributes.attachment_link.readable_text
W3Schools' famous
Browser Statistics
since 2002

The Most Popular Browsers

W3Schools has over 60 million monthly visits.

From the statistics below (collected since 2002) you can read the long term trends of browser usage.

Click on the browser names to see detailed browser information:

Chrome = Google Chrome

Edge = Microsoft Edge

IE = Microsoft Internet Explorer

Firefox = Mozilla Firefox (identified as Mozilla before 2005)

Mozilla = The Mozilla Suite (identified as Firefox after 2004)

Safari = Apple Safari (and Konqueror. Both identified as Mozilla before 2007)

Opera = Opera (from 2011; Opera Mini is included here)

Netscape = Netscape Navigator (identified as Mozilla after 2006)

Statistics Can Be Misleading
"The pure and simple truth is rarely pure and never simple."
Oscar Wilde

W3Schools' statistics may not be relevant to your web site. Different sites attract different audiences. Some web sites attract developers using professional hardware, while other sites attract hobbyists using older computers.

Anyway, data collected from W3Schools' log-files over many years clearly shows the long term trends.

Browsers Developer Tools

Browser's developer tools can be used to inspect, edit and debug HTML, CSS, and JavaScript of the curently-loaded page. To learn more, check out the browser's own manual for developer tools:
Chrome DevTools Microsoft Edge Developer Tools Firefox Developer Tools Safari Web Inspector Opera DevTools
Other Statistics
Mobile browsers statistics Operating system statistics Screen resolution statistics
Computer Speed

The first electrical computer, Z3 (1941), could do 5 instructions per second.

The first electronic digital computer, ENIAC (1945), could do 5000 instructions per second.

Today's computers can do 5 billion instructions per second.

# data[].attributes.attachment_link.description
W3Schools' famousBrowser Statisticssince 2002 W3Schools has over 60 million monthly visits. From the statistics below (collected since 2002) you can read the long term trends of browser usage.

# data[].attributes.attachment_link.readable_text
Please note that this is an older article that discusses JavaScript issues in Internet Explorer versions 6 & 7, along with Firefox versions 2+ & 3.0.
Although the days of long and tedious code branches to target specific browsers in JavaScript are over, once in a while it's still necessary to do some simple code branching and object detection to ensure that a certain piece of code is working properly on a user's machine.

In this article, I'll outine 7 areas where Internet Explorer and Firefox differ in JavaScript syntax.

1. The CSS "float" property

The basic syntax for accessing a specific css property for any given object is object.style.property, using camel casing to replace a hyphenated property. For example, to access the background-color property of a <div> whose ID is "header", we would use the following syntax:

document.getElementById("header").style.backgroundColor= "#ccc";

But since the word "float" is already reserved for use in JavaScript, we cannot access the "float" property using object.style.float. Here is how we do it in the two browsers:
The IE Syntax:

document.getElementById("header").style.styleFloat = "left";

The Firefox Syntax:

document.getElementById("header").style.cssFloat = "left";

2. The Computed Style of an Element

JavaScript can easily access and modify CSS styles that have been set on objects using the object.style.property syntax outlined above. But the limitation of that syntax is that it can only retrieve styles that have been set inline in the HTML or styles that have been set directly by JavaScript. The style object does not access styles set using an external stylesheet. In order to access an object's "computed style", we use the following code:
The IE Syntax:

var myObject = document.getElementById("header");
var myStyle = myObject.currentStyle.backgroundColor;

The Firefox Syntax:

var myObject = document.getElementById("header");
var myComputedStyle = document.defaultView.getComputedStyle(myObject, null);
var myStyle = myComputedStyle.backgroundColor;

3. Accessing the "class" Attribute of an Element

As is the case with the "float" property, our two major browsers use different syntax to access this attribute via the getAttribute method in JavaScript.
The IE Syntax:

var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("className");

The Firefox Syntax:

var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("class");

This syntax would also apply using the setAttribute method.
See a demo page that demonstrates these two different syntaxes
4. Accessing the "for" Attribute of the <label> Tag

Similar to number 3, we have different syntax to access a <label> tag's "for" attribute in JavaScript.
The IE Syntax:

var myObject = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("htmlFor");

The Firefox Syntax:

var myObject = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("for");

5. Getting the Cursor Position

It would be rare that you would want to find the cursor position of an element, but if for some reason you need to, the syntax is different in IE and Firefox. The code samples here are fairly basic, and normally would be part of a much more complex event handler, but they serve to illustrate the difference. Also, it should be noted that the result in IE will be different than that of Firefox, so this method is buggy. Usually, the difference can be compensated for by getting the "scrolling position" - but that's a subject for another post!
The IE Syntax:

var myCursorPosition = [0, 0];
myCursorPosition[0] = event.clientX;
myCursorPosition[1] = event.clientY;

The Firefox Syntax:

var myCursorPosition = [0, 0];
myCursorPosition[0] = event.pageX;
myCursorPosition[1] = event.pageY;

6. Getting the Size of the Viewport, or Browser Window

Sometimes it's necessary to find out the size of the browser's available window space, usually called the "viewport".
The IE Syntax:

var myBrowserSize = [0, 0];
myBrowserSize[0] = document.documentElement.clientWidth;
myBrowserSize[1] = document.documentElement.clientHeight;

The Firefox Syntax:

var myBrowserSize = [0, 0];
myBrowserSize[0] = window.innerWidth;
myBrowserSize[1] = window.innerHeight;

7. Alpha Transparency

Okay, this is not a JavaScript syntax issue - alpha transparency is set via CSS. But when objects fade in and out via JavaScript, this is done by accessing CSS alpha settings, usually inside of a loop. The CSS code that needs to be altered via JavaScript is as follows:
The IE Syntax:

#myElement {
  filter: alpha(opacity=50);
}

The Firefox Syntax:

#myElement {
  opacity: 0.5;
}

So, to access those values via JavaScript, we would use the style object:
The IE Syntax:

var myObject = document.getElementById("myElement");
myObject.style.filter = "alpha(opacity=80)";

The Firefox Syntax:

var myObject = document.getElementById("myElement");
myObject.style.opacity = "0.5";

Of course, as mentioned, normally the opacity/alpha would be changed in the midst of a loop, to create the animating effect, but this simple example clearly illustrates how it's done.

Are There Other Differences?

These are some of the differences I've personally come across either in development or research, but I'm sure there are others. Leave a comment if you think I've left out an important one, and I'll try to update this list, or else do a "Part 2" post.

# data[].attributes.attachment_link.title
7 JavaScript Differences Between Firefox & IE

# data[].attributes.attachment_link.description
Please note that this is an older article that discusses JavaScript issues in Internet Explorer versions 6 & 7, along with Firefox versions 2+ & 3.0. Although the days of long and tedious code branches to target specific browsers in JavaScript are over, once in a while it's still necessary to do some simple code branching and object detection to ensure that a certain piece of code is working properly on a user's machine.

# data[].attributes.attachment_link.readable_text
For the record, I don't think anyone involved in either writing or reading this article is an idiot. But sometimes a topic makes you feel like one, and the engines that power JavaScript code is one of those topics - at least for me.

Writing code for the web sometimes feels a little magical in that we write a sequence of characters and things happen in a browser. But understanding the tech behind the magic can help you better tune your craft as a programmer. At least you might feel slightly less idiotic when trying to explain what is going on behind the scenes in a JavaScript-powered web or mobile stack.

Many years ago when I was a graduate student instructor, I was whining to a professor about not grasping a particularly thorny point of French grammar well enough to teach it to my undergraduate class. I remember her words at the time: "Sometimes, the only way to learn something is to teach it."

Faced with trying to explain to engineers how NativeScript works behind the scenes by using a JavaScript engine at runtime to bridge to native APIs, it's easy to get lost in the weeds. Any JavaScript developer, in fact, might be curious about the engines that underlie this technology that we use on a daily basis. Let's break down what a JavaScript engine does, why different platforms use different engines, how they have evolved over the years, and why we, as developers, should care.

First, a little terminology

A 'JavaScript engine' is often termed a type of virtual machine. A 'virtual machine' refers to the software-driven emulation of a given computer system. There are many types of virtual machines, and they are classified by how precisely they are able to emulate or substitute for actual physical machines.

A 'system virtual machine', for example, provides a complete emulation of a platform on which an operating system can be executed. Mac users are familiar with Parallels, a system virtual machine that allows you to run Windows on your Mac.

A 'process virtual machine', on the other hand, is less fully-functional and can run one program or process. Wine is a process virtual machine that allows you to run Windows applications on a Linux machine, but does not provide an entire Windows OS on a Linux box.

A JavaScript engine is a kind of process virtual machine that is designed specifically to interpret and execute JavaScript code.

Note: it's important to differentiate between the layout engines that power a browser by laying out web pages, versus the lower-level JavaScript engine that interprets and executes code. A good explanation is found here.

So what, exactly, is a JavaScript engine, and what does it do?

The basic job of a JavaScript engine, when all is said and done, is to take the JavaScript code that a developer writes and convert it to fast, optimized code that can be interpreted by a browser or even embedded into an application. JavaScriptCore, in fact, calls itself an "optimizing virtual machine".

More precisely, each JavaScript engine implements a version of ECMAScript, of which JavaScript is a dialect. As ECMAScript evolves, so do JavaScript engines. The reason there are so many different engines is each one is designed to work with a different web browser, headless browser, or runtime like Node.js.

You're probably familiar with web browsers, but what's a headless browser? It's a web browser without a graphic user interface. They are useful for running automated tests against your web products. A good example is PhantomJS. And where does Node.js fit into this? Node.js is an asynchronous, event-driven framework that allows you to use JavaScript on the server-side. Since they are JavaScript-driven tools, they are powered by JavaScript engines.

Given the definition of a virtual machine above, it makes sense to term a JavaScript engine a process virtual machine, since its sole purpose is to read and compile JavaScript code. This doesn't mean that it's a simple engine. JavaScriptCore, for example, has six 'building blocks' that analyze, interpret, optimize, and garbage collect JavaScript code.

How does this work?

This depends, of course, on the engine. The two main engines of interest to us, because they are leveraged by NativeScript, are WebKit's JavaScriptCore and Google's V8 engine. These two engines handle processing code differently.

JavaScriptCore performs a series of steps to interpret and optimize a script:

1. It performs a lexical analysis, breaking down the source into a series of tokens, or strings with an identified meaning.

2. The tokens are then analyzed by the parser for syntax and built into a syntax tree.

3. Four JIT (just in time) processes then kick in, analyzing and executing the bytecode produced by the parser.

Huh? In simple terms, this JavaScript engine takes your source code, breaks it up into strings (a.k.a. lexes it), takes those strings and converts them into bytecode that a compiler can understand, and then executes it.

Google's V8 engine, written in C++, also compiles and executes JavaScript source code, handles memory allocation, and garbage collects leftovers. Its design consists of two compilers that compile source code directly into machine code:

1. Full-codegen: a fast compiler that produces unoptimized code

2. Crankshaft: a slower compiler that produces fast, optimized code.

If Crankshaft determines that the unoptimized code generated by Full-codegen is in need of optimization, it replaces it, a process known as 'crankshafting'.

Fun fact: a crankshaft is an integral part of the internal combustion engines used in the automotive industry. A well-known engine of this type used in higher-performance vehicles is the V8.

Once machine code is produced by the compilation process, the engine exposes all the data types, operators, objects, and functions specified in the ECMA standard to the browser, or any runtime that needs to use them, like NativeScript.

What JavaScript engines are out there?

There is a dizzying variety of JavaScript engines available to analyze, parse and execute your client-side code. With every browser version release, the JavaScript engine might be changed or optimized to keep up with the state of the art in JavaScript code execution.

It's useful to remember, before getting totally confused by the names given to these engines, that a lot of marketing push goes into these engines and the browsers they underlie. In this useful analysis of JavaScript compilation, the author notes wryly: "In case you didn't know, compilers are approximately 37% composed of marketing, and rebranding is one of the few things you can do to a compiler, marketing-wise, hence the name train: SquirrelFish, Nitro, SFX..."

While keeping in mind the heavy marketing influence in naming and renaming these engines, it's useful to note a few of the major events in the history of the JavaScript engine. I've compiled a handy chart for you:

*JavaScriptCore was rewritten as SquirrelFish, rebranded as SquirrelFish Extreme also called Nitro. It's still a true statement however to call JavaScriptCore the JavaScript engine that underlies WebKit implementations (such as Safari).

**iOS developers should be aware that Mobile Safari leverages Nitro, but UIWebView does not include JIT compilation, so the experience is slower. With iOS8, however, developers can use WKWebView which includes access to Nitro, speeding up the experience considerably. Hybrid mobile app developers should be able to breathe a little easier.

***One of the factors in the decision to split io.js from Node.js had to do with the version of V8 that would be supported by the project. This continues to be a challenge, as outlined here.

Why should we care?
The goal of a JavaScript engine's code parsing and execution process is to generate the most optimized code in the shortest possible time.
Bottom line, the evolution of these engines parallels our quest to evolve the web and mobile spheres to make them as performant as possible. To track this evolution, you can see how various engines perform in benchmarking graphs such as those produced on arewefastyet.com. It's interesting, for example, to compare Chrome's performance when powered by V8 versus a non-Crankshafted engine.

Any web developer needs to be aware of the differences inherent in the browsers that display the code that we work so hard to produce, debug, and maintain. Why do certain scripts work slowly on one browser, but more quickly on another?

Mobile developers, similarly, especially those who write hybrid mobile apps using a webview to display their content, or those using a runtime like NativeScript, will want to know what engines are interpreting their JavaScript code. Mobile web developers should understand the limitations inherent to and possibilities offered by the various browsers on their small devices. Keeping up with the changes in JavaScript engines will really pay off as you evolve as a web, mobile, or app developer.
Header image courtesy of Charlie Day

# data[].attributes.attachment_link.title
A Guide to JavaScript Engines for Idiots -

# data[].attributes.attachment_link.description
For the record, I don't think anyone involved in either writing or reading this article is an idiot. But sometimes a topic makes you feel like one, and the engines that power JavaScript code is one of those topics - at least for me.

# data[].attributes.attachment_link.readable_text
The purpose of this research is to give a clear overview of how modern Javascript engines run, comparison between the different engines and a quick guide on writing well-performing code.

This research analyses the Javascript engines - Chrome V8 [1], Microsoft Chakra [2] and Microsoft Chakra Core [3], and put in practices to ensure that these engines can easily profile and optimize the codes you have written, allowing better performance.

Test Platform Specifications

Operating System: Windows Server 2016 Technical Preview 2

Disk: Corsair Force GS 128GB SSD

CPU: Intel i3-4130 @ 3.40 GHz

RAM: 8GB

Chrome: 49.02623.112 m

Edge: 20.10514.0.0

NodeJS: 5.80

NodeChakra: 6.0.0-pre6

Summary

Both engines profile code and perform Just in time (JIT) compilation which produces optimized machine codes.

V8 performs slightly better than Chakra and Chakra Core.

Write predictable code so that they can be easily profiled.

Javascript Engines

As a quick overview, Javascript engines are embedded in browsers and web servers, such as NodeJS [4], to allow run-time compilation and execution of Javascript code. These engines consist of an interpreter and an optimized compiler.

Both Chrome V8 and Chakra Core are open source Javascript engines, which means developers and researchers can "look under the hood" to understand what exactly is happening. The following sections provide a detailed analysis of both Javascript engines.

Google Chrome V8

The V8 engine has an interpreter named "Ignition" [5]. This interpreter is used for interpreting and executing low level bytecode. Bytecodes, although slower, are smaller than machine codes and requires lesser compilation time.

In order to compile Javascript to bytecode, the Javascript code has to be parsed to generate its Abstract Syntax Tree (AST). The interpreter has an accumulator register, which allows it reduce the size of the bytecode. The overall design makes Ignition a highly efficient interpreter.

Whereas its optimizing JIT compiler is named "TurboFan" [6]. TurboFan will profile the code and see if it is used multiple times throughout the entire Javascript execution. If it is, the code will be dynamically optimized immediately into machine code, without any intermediate binary code. If it is a one-time executed "non-hot" code, it will only be compiled into binary code.

By reducing unnecessary generation of machine code, the Javascript engine will be able to run more efficiently. The profiling makes use of hidden classes, which are classes that can be instantiated to create objects with fixed variable offsets. Fixed offsets, rather than dynamic lookup, allows codes to be read in a very efficient manner without having to resolve to a memory location for a variable.

However, if the code being profiled is acting in a way which is not as predicted, the engine will fallback to normal bytecode interpretation, and this causes it to slow down. Only after some period of time will V8 then attempt to profile other codes. Therefore, developers should always try to write their algorithms and code that runs in a predictable manner.

Garbage collection is also done in a "stop-the-world", generational way. This means that before the JavaScript engine does garbage collection, all processing of JavaScript will be paused and the garbage collector will find objects and data that are no longer referenced and collect them. This ensures that garbage collection is done in an accurate and efficient way.

Chakra Core

Chakra Core has certain components of Chakra and is modified to report certain data differently [7]. Instead of COM-based diagnostic APIs, Chakra Core provides JSON-based diagnostic APIs which allow more applications with JSON parsers to support Chakra Core.

The architecture is also designed to have multi-tier support. This allows Chakra Core to do parallel JIT compilation and utilize as much resources as possible to finish its task, as fast as it can. Chakra Core first reads through the Javascript code syntax and parses it to generate its AST. After the AST is generated, the code is passed to the bytecode generator and then the bytecode gets profiled. This is different from V8 which has a decision process that decides whether a piece of code should be profiled and optimized or should be turned into bytecode.

During the profiling process, the interpreter attempts to send the code to parallel JIT compilers. There are two types of JIT compilers available: simple JIT compiler, and full JIT compiler.

During run time, the Javascript code will undergo a simple JIT compile, where the codes are compiled quickly without much optimization. Whilst full JIT will also happen concurrently, compiling the Javascript code in an optimized manner - the full JIT takes more time but produces better machine code that is generated based on the profile produced by the profiling interpreter.

If full JIT compilation fails because the code does something that is out of its profile, the engine will bailout to run the codes that are JIT'd using the simple JIT compiler. To prevent bailout of full JIT to simple JIT codes from happening, developers should write their code so that that it does processing in a predictable manner.

As for garbage collection, it is done in a generational mark-and-sweep manner. When garbage collection happens, a foreground and background thread will be spawned to carry out different executions. The background garbage collector will do a mark, rescan and mark to find objects that should be cleaned up.

Benchmark

The benchmark and tests were performed using the Octane 2.0 Benchmark [8], which measures the performance of a Javascript engine through running code that is used in the modern era's web applications.

Benchmarks are an incomplete representation of the performance of the engine and should only be used for a rough gauge. The benchmark results may not be 100% accurate and may also vary from platforms to platforms.

Through extensive, iterative tests on Google Chrome on V8 engine, NodeJS on V8 engine, Microsoft Edge on Chakra engine and NodeJS on Chakra Core engine, here are the results.

Google Chrome V8

NodeJS V8 Octane 2.0 Score: 16,639

Google Chrome Browser V8 Octane 2.0 Score: 21,800

Chakra

NodeJS Chakra Core Octane 2.0 Score: 15,462

Microsoft Edge Chakra Octane 2.0 Score: 20,700

Examples

The following examples show how Javascript codes can be written to avoid breaking profiling, therefore, improving performance. Detailed examples can also be found on Github [9].

/* In this example, we show that good code should not create new variables of the object.
 * This is to prevent an additional hidden class from being created.
*/

// Bad code
function Person(name, age) {
    this.name = name;
    this.age = age;
}

var mary = new Person(&quot;mary&quot;, 22);
var bryan = new Person(&quot;bryan&quot;, 22);
bryan.blood = &quot;AB&quot;; // Blood was never declared, new hidden class &quot;person&quot; has to be declared

// Good code
function Person(name, age) {
    this.name = name;
    this.age = age;
    this.blood = &quot;&quot;; // Blood is declared
}

var mary = new Person(&quot;mary&quot;, 22);
var bryan = new Person(&quot;bryan&quot;, 22);
bryan.blood = &quot;AB&quot;;

Performance Measurement

There are several tools out there which can help you out with testing out the performance of your Javascript code. An accurate and convenient way to do it is to make use of the Javascript function - console.time [10] or performance.now [11], which works on most modern browsers and newer NodeJS versions. For a more accurate, non-DOM based performance testing, use the V8 internal profiler [12].

Sources

[1] - https://developers.google.com/v8/
[2] - http://www.thewindowsclub.com/microsofts-new-javascript-engine-codenamed-chakra-for-internet-explorer-9
[3] - https://github.com/microsoft/ChakraCore
[4] - https://nodejs.org/en/
[5] - https://docs.google.com/document/d/11T2CRex9hXxoJwbYqVQ32yIPMh0uouUZLdyrtmMoL44/edit?ts=56f27d9d#heading=h.6jz9dj3bnr8t
[6] - http://v8project.blogspot.de/2015/07/digging-into-turbofan-jit.html
[7] - https://github.com/Microsoft/ChakraCore/wiki/Architecture-Overview
[8] - https://developers.google.com/octane/
[9] - https://github.com/GIANTCRAB/Javascript-Performance-Test/
[10] - https://developer.mozilla.org/en-US/docs/Web/API/Console/time
[11] - https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
[12] - https://github.com/v8/v8/wiki/V8%20Profiler

# data[].attributes.attachment_link.title
Javascript Engine & Performance Comparison (V8, Chakra, Chakra Core) - RHD Blog

# data[].attributes.attachment_link.description
The purpose of this research is to give a clear overview of how modern Javascript engines run, comparison between the different engines and a quick guide on writing well-performing code. This research analyses the Javascript engines - Chrome V8 [1], Microsoft Chakra [2] and Microsoft Chakra Core [3], and put in practices to ensure that these ...

# data[].attributes.attachment_link.title
Free online browser speed test - SPEED BATTLE

# data[].attributes.attachment_link.description
SPEED-BATTLE measures online the speed of JavaScript in your browser and shows a comparison to previous visitors

# data[].attributes.body
Gives a view into how it is called by the browser too

# data[].attributes.attachment_link.readable_text
About The Author

Chris is a Developer Evangelist living in London, England, who writes about Javascript development, accessibility, and all things open web. After several years ... More about Christian Heilmann...

Using JavaScript has become increasingly easy over the last few years. Whereas back in the day we needed to know the quirks of every browser, now many libraries such as jQuery, YUI, Dojo and MooTools allow someone who doesn't even know JavaScript to spruce up boring HTML documents with impressive and shiny effects. By piggy-backing on the CSS selector engine, we have moved away from the complexity and inconsistencies of the DOM and made things much easier.

If you look at some of the code that has been released, though, we do seem to have taken a step backwards. In gaining easier access, we also became a bit sloppy with our code. Finding clearly structured, easy-to-maintain jQuery code is quite tough, which is why many plug-ins do the same thing. Writing one yourself is faster than trying to fathom what other developers have done.

Be sure to check out the following articles:

The rules for solid, maintainable and secure JavaScript haven't changed, though. So, let's run through the seven sins of JavaScript development that will bite you in the backside when you have to maintain the code later on or hand it over to another party.

Meet Smashing Book 6 with everything from design systems and accessible single-page apps to CSS Custom Properties, Grid, Service Workers, performance, AR/VR and responsive art direction. New frontiers in front-end and UX with Marcy Sutton, Harry Roberts, Laura Elizabeth and many others.

Table of Contents →

We've all had to work with code written by other people. We have despaired over the lack of maintainability and documentation as well as weird logic. Funny enough, as developers, we started to see this as normal and got used to ignoring other people's work and instead writing new code for the same problems over and over, as if we were subconsciously trying to secure our jobs by leaving behind unmaintainable code-code that only we understood, while complaining that no good solutions were out there.

Sins Of Our Fathers: Browser-Specific Code

One of the main obstacles that kept us from evolving as developers was that JavaScript was largely browser-specific.

This was mainly because browsers did not support the standards (or were shipped before the governing bodies agreed on standards at all), and because we had to deliver our work before the competition and without extending the overly optimistic deadline set by our project managers.

This happens to be one reason why Internet Explorer 6 refuses to die. Hundreds of expensive software packages that are being used in offices worldwide were built when this browser was state of the art. This-and the monoculture that advocated using one software vendor for everything from the operating system to documents to spreadsheets to the browser-is the reason why companies now can't simply discontinue support for it. It also means that newer versions of IE will always have to support the rendering mistakes of IE6 in one way or another. IE6 is the Frankenstein of the Internet, haunting its creators, terribly misunderstood by the townsfolk, who would sooner kill it, burn it and dance around it than make any sense of it.

The good news is that you won't find many scripts these days that begin with if(document.all){} and continue with else if(document.layers){}. If you do find one, please send its creator a brief email encouraging them to move on or, better yet, to redirect their website to a better script that is actually being maintained.

Libraries to the Rescue

The job of JavaScript libraries such as jQuery, YUI, MooTools, Dojo and Glow is to make JavaScript development predictable and to relieve developers of the living hell that we call browser support. In other words, they fix random bugs in browsers and free us to adopt standards without worrying that certain browsers won't recognize them.

For example, the DOM method getElementById(id) should be straightforward: find the element with the ID id and return it. But because some versions of IE and Opera also return elements that have the name attribute of id, jQuery solves the problem this way:

var elem; elem = document.getElementById( match[2] ); if ( elem ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; }

This is where libraries are awfully useful and is why JavaScript libraries are here to stay. Browsers will always do things wrong, and old browsers will not be upgraded by end users, either because of the aforementioned company regulations or because people simply don't care to keep up with the times.

So, while the practice of building software for certain browsers is on the decline (at least for JavaScript-with CSS, we have a whole other headache ahead of us), we still have to be mindful of certain sins.

Sin #1: Not Playing Nice With Other Scripts

Here's the first one, which we still see a lot of on the Web. Sadly, it is very common in demo code for APIs and Web services: global variables, functions and DOM-1 event handlers.

What do I mean by these? Consider the following:

Every script in the HTML document has the same rights as the others and can, if need be, overwrite what other scripts have done before.

If you define a variable or function name, and some other include uses the same name, the initial one will be overwritten.

The same applies to event handlers if you attach them the old-school onEvent way.

Say you have the script script_one.js:

x = 5; function init(){ alert('script one init'); document.getElementsByTagName('h1')[0].onclick = function(){ this.style.background = 'blue'; } } alert('x is '+x); window.onload = init;

And immediately after this one, you include another script, script_two.js:

x = 10; function init(){ alert('script two init'); document.getElementsByTagName('h1')[0].onclick = function(){ this.style.color = 'white'; } } alert('x is '+x); window.onload = init;

If you open this document in a browser, you will find that x turns from 5 to 10 and that the first init() is never called. The script two init alert() does not come up, nor does the h1 get a blue background when you click it. Only the text turns to white, which renders it invisible.

The solution is not to use onEvent handlers, but rather the proper DOM level 2 event handlers (they don't work in IE, but let's not worry about that at the moment-remember, this is what libraries are for). Furthermore, wrap your functions in another with a more unique name to prevent them from overriding each other.

var scriptOne = function(){ var x = 5; function init(){ alert('script one init'); document.getElementsByTagName('h1')[0].addEventListener( 'click', function(e){ var t = e.target; t.style.background = 'blue'; }, false ); } alert('x inside is '+x); return {init:init}; }(); window.addEventListener('load',scriptOne.init,false); alert('x outside is '+x); var scriptTwo = function(){ var x = 10; function init(){ alert('script two init'); document.getElementsByTagName('h1')[0].addEventListener( 'click', function(e){ var t = e.target; t.style.color = 'white'; }, false ); } alert('x inside is '+x); return {init:init}; }(); window.addEventListener('load',scriptTwo.init,false); alert('x outside is '+x);

If you run this in a browser (not Internet Explorer 6), everything will come up as you expect: x is first 5, then 10 on the inside, and the heading turns blue and white when you click it. Both init() functions are called, too.

You also get an error. Because x is not defined outside the functions, the alert('x outside is '+x); never works.

The reason is that by moving the x into the scriptOne and scriptTwo functions and adding the var keyword in front of them, we have made them a part of those functions but hid them from the outside world. This is called a closure and is explained in detail here. It is probably the most powerful feature of JavaScript.

Using closures and var keywords, you won't have the problem of variables with similar names overriding each other. This also applies in jQuery: you should namespace your functions.

This can be tough to grasp, so let's look at a simpler example:

var x = 4; var f = 3; var me = 'Chris'; function init(){} function load(){}

All of these are global variables and functions now. Any other script having the same variables will override these.

You can nest them in an object to avoid this:

var longerAndMoreDistinct = { x : 4, f : 3, me : 'Chris', init : function(){}, load : function(){} }

That way, only the longerAndMoreDistinct is global. If you want to run this function, you now have to call longerAndMoreDistinct.init() instead of init(). You can reach me as longerAndMoreDistinct.me and so on.

I don't like this because I have to switch from one notation to another. So, we can do the following:

var longerAndMoreDistinct = function(){ var x = 4; var f = 3; var me = 'Chris'; function init(){} function load(){} }();

You define longerAndMoreDistinct as the outcome of a function without a name that gets immediately executed (this is the () on the last line). This now means that all of the variables and functions inside exist only in this world and cannot be accessed from outside at all. If you want to make them accessible from outside, you need to return them to the outside world:

var longerAndMoreDistinct = function(){ var x = 4; var f = 3; var me = 'Chris'; function load(){} return { init:function(){} } }();

Now init() is available as longerAndMoreDistinct.init() again. This construct of wrapping things in an anonymous function and returning some of them is called the Module pattern, and it keeps your variables safe. Personally, I still hate the shift in syntax, so I came up with the revealing module pattern. Instead of returning the real function, all I do is return a pointer to it:

var longerAndMoreDistinct = function(){ var x = 4; var f = 3; var me = 'Chris'; function load(){} function init(){} return { init:init } }();

This way, I can make things either available or not available simply by adding to the object that is returned.

If you don't need to give anything to the world and just want to run some code and keep all of your variables and function names safe, you can dispense with the name of the function:

(function(){ var x = 4; var f = 3; var me = 'Chris'; function load(){} function init(){} })();

Using var and wrapping code in this construct makes it inaccessible to the outside world, but still makes it execute.

You may find this to be complex stuff, but there is a good way to check your code. JSLint is a validator for JavaScript, much like the HTML or CSS validators, and it tells you all the things that might be wrong with your code.

Sin #2: Believing Instead Of Testing

The next big sin related to implementing JavaScript is expecting everything to go right: every parameter being in the right format, every HTML element you try to enhance being truly available, and every end user entering information in the right format. This will never be the case, and that last assumption is an especially bad one because it allows malicious users to inject dangerous code.

When you write JavaScript and give it to the world or integrate it in a product that will be maintained by a third party, a little paranoia is a good thing.

typeof is your friend. Regular expressions are your friend. indexOf(), split and length are your friends. In other words, do everything you can to make sure that incoming data is the right format.

You will get a lot of errors with native JavaScript; if you do anything wrong, you'll know what happened. The annoying thing about most JavaScript libraries is that when they fail to execute some functionality, they do it silently. The maintainer is left guessing and has to run through all the code and start debugging with stop points (or-shudder!- alerts()) to reverse-engineer where you entered instable code. To avoid this, simply wrap whatever you can in a test case rather than try to access it.

Sin #3: Using The Wrong Technology For The Job

The biggest problem with JavaScript happens when you use the wrong tool for the job. It makes maintenance a nightmare and deteriorates the code's quality. Use tools for the jobs they were meant for. This means:

Absolutely essential content and mark-up should be in HTML, regardless of the environment it will be displayed in.

Any "look and feel" elements should be maintainable through CSS. You should not have to scour through JavaScript to change a color.

Any interaction with the user that goes beyond hover effects (which, by definition, are an invitation to interact and not the interaction itself-because they are inaccessible to keyboard users) should be done with JavaScript.

The main reason why this is still a valid, pragmatic and sensible approach to development is that as Web technologies get muddled (for example, you can create content with CSS and JavaScript, animate and transform in CSS and-if you really want-paint with HTML), people's skills and interests in these different technologies vary quite a bit.

Semantic mark-up buffs are not much interested in applying closures in JavaScript. JavaScript developers are not much interested in the order of elements in CSS. And CSS fans aren't keen to learn how to make a JavaScript animation run flicker-free.

This results in the same problems being solved over and over again, only with different technologies. This is a market-wide problem: a lot of state-of-the-art Canvas tricks were done in Flash years ago, their impact debated and their problems fixed.

My favorite instance of this is when people write loops to hide a lot of elements on the page to make them available later on.

Say this is your HTML:

<h2>Section 1</h2> <div class="section"> <p>Section 1 content</p> </div> <h2>Section 2</h2> <div class="section"> <p>Section 2 content</p> </div> <h2>Section 3</h2> <div class="section"> <p>Section 3 content</p> </div> <h2>Section 4</h2> <div class="section"> <p>Section 4 content</p> </div>

The normal jQuery solution for this would be:

$(document).ready(function(){ $('.section').hide(); $('h2').click(function(e){ $(this).next().toggle(); }) });

And then you realize that making the style of the current section deviate from that of the other sections would be great.

$(document).ready(function(){ $('.section').hide(); $('h2').click(function(e){ $(this).next().toggle(); $(this).next().css('background','#ccc'); $(this).next().css('border','1px solid #999'); $(this).next().css('padding','5px'); }) });

A few things are wrong with this. For starters, you've made it hard to maintain this by controlling the look and feel in JavaScript, not CSS (more on this later). Secondly, performance: while jQuery is amazingly speedy, a lot of code is still hidden under the hood in $('.section').hide(). The last, and very painful, performance issue is the copied and pasted lines that set the CSS. Don't ask jQuery to find the next sibling four times and do something to it. You could store the next() in a variable, but even that is not needed if you chain. If you really need to set a lot of CSS in jQuery, use a map:

$(document).ready(function(){ $('.section').hide(); $('h2').click(function(e){ $(this).next().toggle().css({ 'background':'#ffc', 'border':'1px solid #999', 'padding':'5px' }); }) });

What if you then want to allow only one of them to be open at any time? Inexperienced developers would do something like this:

$(document).ready(function(){ $('.section').hide(); $('h2').click(function(e){ $('.section').hide(); $(this).next().toggle().css({ 'background':'#ffc', 'border':'1px solid #999', 'padding':'5px' }); }) });

This does the job, but you're looping around the document and accessing the DOM a lot, which is slow. You can alleviate this by keeping the current open section in a variable:

$(document).ready(function(){ var current = false; $('.section').hide(); $('h2').click(function(e){ if(current){ current.hide(); } current = $(this).next(); current.toggle().css({ 'background':'#ffc', 'border':'1px solid #999', 'padding':'5px' }); }) });

Predefine the current section as false, and set it when you click the first heading. You would then hide current only if it is true, thereby removing the need for another loop through all elements that have the class section.

But here is the interesting thing: if all you want is to show and hide sections, you don't need any looping at all! CSS already goes through the document when it renders and applies classes. You just need to give the CSS engine something to hang on to, such as a class for the body:

$(document).ready(function(){ $('body').addClass('js'); var current = null; $('h2').click(function(e){ if(current){ current.removeClass('current'); } current = $(this).next().addClass('current'); }) });

By adding the class js to the body of the document and toggling the class current for the current section, you maintain control of the look and feel in CSS:

<style type="text/css" media="screen"> .section{ border:1px solid #999; background:#ccc; } .js .section{ display:none; } .js .current{ display:block; border:1px solid #999; background:#ffc; } </style>

The beauty of this is that the handle will be re-usable by the CSS designer and maintainer. Anything without the .js selector would be the non-scripting-enabled version of a part of the document, and anything with the .js selector is applied only when JavaScript is available. And yes, you should think about the case when it is not.

Sin #4: Depending On JavaScript And Certain Input Devices

There is quite a discussion about the need to consider non-JavaScript environments in this day and age, but here is a fact: JavaScript can be turned off, and any JavaScript could break the page for the other scripts that are included. Given the flakiness of code out there that may be running alongside yours and the instability of wireless and mobile connections, I for one want to build one thing: code that works.

So, making sure that the most basic usage of your product does not depend on JavaScript is not just nice to have but essential if you expect people to actually use the product.

Absolutely nothing is wrong with using JavaScript heavily. On the contrary, it makes the Web much smoother and saves us a lot of time if done right. But you should never promise functionality that doesn't work. And if you rely on JavaScript, this is exactly what you're doing. I've already covered the effects of bad JavaScript in detail in the AJAX, JavaScript testing and security articles here on Smashing Magazine, but once again here are some simple steps you can take to make sure you don't break your promise to end users:

Anything vital to the functionality of your product should not require JavaScript. Forms, links and server-side validation and re-direct scripts are your friends.

If something depends on JavaScript, build it with JavaScript and add it to the document using the DOM or the equivalent method in your library of choice.

If you add JavaScript functionality, make sure it works with the keyboard and mouse. Click and submit handlers are bullet-proof, whereas key and mouse events are flaky and don't work on mobile devices.

By writing clever back-end code that recognizes when data is required by JavaScript rather than building APIs that render HTML, you avoid having to do double-maintenance, which is an argument that many of the "Everyone enables JavaScript" zealots bring up a lot. For proof of this, check out the presentation on building Web applications using YQL and YUI that I gave a few weeks ago (video in English and German).

When JavaScript Dependence Is Okay (to a Degree)

A lot of misunderstanding about JavaScript dependence stems from people making blanket statements based on the environments they work in.

If you are a Google engineer working on Gmail, you would be hard pressed to think of why you would even bother working without JavaScript. The same goes for widget developers who work on OpenSocial widgets, mobile applications, Apple widgets and Adobe Air. In other words, if your environment already depends on JavaScript, then by all means don't bother with a fall-back.

But do not take these closed environments and edge-case applications as the standard by which we should be measuring JavaScript. JavaScript's greatest power and greatest problem is its versatility. Saying that all websites can stand JavaScript because Gmail needs it is like saying that all cars should have a start button because they work great in Hybrids, or that hybrid cars should have massive tanks and cow catchers because they work great on Hummers. The technical feature set of a product depends on its implementation and target market. Different applications have different base functionality that needs to be satisfied in order to reach the largest audience and not block people out.

Consider the Use Cases and Maintenance

One fascinating aspect of JavaScript-dependent code is that, in many cases, people have simply not considered all the use cases (here's a great example). Take the following HTML:

Without JavaScript, this does nothing whatsoever. There is no sensible action attribute, and the text field has no name attribute. So, even when you send the form off, the server won't get the information that the user has entered.

Using jQuery and a JSON data source such as YQL, you can do a pure JavaScript search with this:

$('#s').click(function(event){ event.preventDefault(); $('<ul/>').appendTo('#results'); var url = $.getJSON('http://query.yahooapis.com/v1/public/yql?'+ 'q=select%20abstract%2Cclickurl%2Cdispurl%2Ctitle%20'+ 'from%20search.web%20where%20query%3D%22'+ $('#search').val() + '%22&format=json&'+ 'callback=?', function(data){ $.each(data.query.results.result, function(i,item){ $('<li><h3><a href="'+item.clickurl+'">'+ item.title+' ('+item.dispurl+')</a></h3><p>'+ (item.abstract || ') +'</p></li>'). appendTo("#results ul"); }); }); });

This works... unless of course you are like me and prefer to send forms by hitting "Enter" rather than clicking the "Submit" button. Unless I tab through the whole form and focus on the "Submit" button, I get nothing.

So, that's the first thing to fix. If you create forms, never use a click handler on the button. Instead, use the submit event of the form. This catches both the clicking "Submit" and hitting "Enter" cases. With one change, you now support all of the keyboard users out there, and the whole change is contained in the first line:

$('#f').submit(function(event){ event.preventDefault(); $('<ul/>').appendTo('#results'); var url = $.getJSON('http://query.yahooapis.com/v1/public/yql?'+ 'q=select%20abstract%2Cclickurl%2Cdispurl%2Ctitle%20'+ 'from%20search.web%20where%20query%3D%22'+ $('#search').val() + '%22&format=json&'+ 'callback=?', function(data){ $.each(data.query.results.result, function(i,item){ $('<li><h3><a href="'+item.clickurl+'">'+ item.title+' ('+item.dispurl+')</a></h3><p>'+ (item.abstract || ') +'</p></li>'). appendTo("#results ul"); }); }); });

We've now covered the first case. But without JavaScript, the form still doesn't do anything. And another problem brings us to the next sin of writing JavaScript.

Sin #5: Making Maintenance Unnecessarily Hard

One thing that keeps great code off the Web is that our work environment, deadlines and hiring practices condition developers to build code for quick release, without considering how difficult maintaining that code will be later on. I once called JavaScript the village bicycle of Web design ( slides here): anyone can go for a ride. Because the code is available in the open, future maintainers will be able to mess around with it and extend it any way they like.

The sad thing is that the harder your code is to maintain, the more errors will be added to it, leading it to look more like alphabet soup than organized script.

Take the above example. Those of you who haven't worked with YQL and JSON-P for cross-domain AJAX undoubtedly had a "What?" moment looking at the code. Furthermore, keeping a lot of HTML in JavaScript easy to follow is hard, and guess what is the first thing to change when a new design for the page comes along? Exactly: the HTML and CSS. So, to make it easier to maintain, I for one would shift all of the work to the back end, thus making the form work without JavaScript and keeping maintenance of all the HTML in the same document:

<?php if(isset($_GET['search'])){ $search = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED); $data = getdata($search); if($data->query->results){ $out = '<ul>'; foreach($data->query->results->result as $r){ $out .= "<li> <h3> <a href="{$r->clickurl}">{$r->title} <span>({$r->dispurl})</span> </a> </h3> <p>{$r->abstract}</p> </li>"; } $out .= '</ul>'; } else { $out = '<h3>Error: could not find any results</h3>'; } } if($_SERVER['HTTP_X_REQUESTED_WITH']!='){ echo $out; die(); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax Search with PHP API</title> <link rel="stylesheet" href="styles.css" type="text/css"> </head> <body> <form action="independent.php" id="f"> <div> <label for="search">Search</label> <input type="text" value="kittens" name="search" id="search"> <input type="submit" id="s" value="Go"> </div> </form> <div id="results"><?php if($out!='){echo $out;}?></div> <script src="jquery.js"></script> <script src="ajaxform.js"></script> </body> </html> <?php function getdata($search){ $url = 'http://query.yahooapis.com/v1/public/yql?'. 'q=select%20abstract%2Cclickurl%2Cdispurl%2Ctitle%20'. 'from%20search.web%20where%20query%3D%22'.$search.'%22'. '&format=json'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $data = json_decode($output); return $data; } ?>

Someone who doesn't understand PHP at all should still be able to change the HTML display without breaking the code. With this in place, the JavaScript boils down to a very simple script:

$('#f').submit(function(event){ event.preventDefault(); $.get('independent.php?search=' + $('#search').val(), function(data) { $('#results').html(data); } ); });

The normal way to make code more maintainable is to move everything that is likely to change away from the main functional part of the script into a configuration object at the very top of the script. You can return this as an object to the outside world to allow people to set it before they initialize the main functionality.

So, one change we can make to our earlier example-albeit a small one now, but that can change quickly when more requirements come in-is to have a configuration section right up front that defines the CSS classes in use:

$(document).ready(function(){ /* Configuration object - change classes, IDs and string here */ var config = { /* CSS classes that get applied dynamically */ javascriptenabled:'js', currentsection:'current' } /* functionality starts here */ $('body').addClass(config.javascriptenabled); var current = null; $('h2').click(function(e){ if(current){ current.removeClass(config.currentsection); } current = $(this).next().addClass(config.currentsection); }) });

For more information on configuration objects and why they rock for maintenance, check out the blog post " Providing Script Configuration Inline and Programatically ".

In summary, go over your code once more when you think you've finished with it and the next person is about to take it over.

Sin #6: Not Documenting Your Code

"Good code documents itself" is a terribly common and misguided belief. In my years as a developer, I've found that my style of coding has changed constantly. What was common knowledge and best practice in 2004 might be forgotten or even considered poor style these days.

<h2>Section 2</h2> <div class="section"> <p>Section 2 content</p> </div>

<h2>Section 3</h2> <div class="section"> <p>Section 3 content</p> </div>

<h2>Section 4</h2> <div class="section"> <p>Section 4 content</p> </div>

The normal jQuery solution for this would be:

$(document).ready(function(){ $('.section').hide(); $('h2').click(function(e){ $(this).next().toggle(); }) });

And then you realize that making the style of the current section deviate from that of the other sections would be great.

$(document).ready(function(){ $('.section').hide(); $('h2').click(function(e){ $(this).next().toggle(); $(this).next().css('background','#ccc'); $(this).next().css('border','1px solid #999'); $(this).next().css('padding','5px'); }) });

A few things are wrong with this. For starters, you've made it hard to maintain this by controlling the look and feel in JavaScript, not CSS (more on this later). Secondly, performance: while jQuery is amazingly speedy, a lot of code is still hidden under the hood in $('.section').hide(). The last, and very painful, performance issue is the copied and pasted lines that set the CSS. Don't ask jQuery to find the next sibling four times and do something to it. You could store the next() in a variable, but even that is not needed if you chain. If you really need to set a lot of CSS in jQuery, use a map:

$(document).ready(function(){ $('.section').hide(); $('h2').click(function(e){ $(this).next().toggle().css({ 'background':'#ffc', 'border':'1px solid #999', 'padding':'5px' }); }) });

What if you then want to allow only one of them to be open at any time? Inexperienced developers would do something like this:

$(document).ready(function(){ $('.section').hide(); $('h2').click(function(e){ $('.section').hide(); $(this).next().toggle().css({ 'background':'#ffc', 'border':'1px solid #999', 'padding':'5px' }); }) });

This does the job, but you're looping around the document and accessing the DOM a lot, which is slow. You can alleviate this by keeping the current open section in a variable:

$(document).ready(function(){ var current = false; $('.section').hide(); $('h2').click(function(e){ if(current){ current.hide(); } current = $(this).next(); current.toggle().css({ 'background':'#ffc', 'border':'1px solid #999', 'padding':'5px' }); }) });

Predefine the current section as false, and set it when you click the first heading. You would then hide current only if it is true, thereby removing the need for another loop through all elements that have the class section.

But here is the interesting thing: if all you want is to show and hide sections, you don't need any looping at all! CSS already goes through the document when it renders and applies classes. You just need to give the CSS engine something to hang on to, such as a class for the body:

$(document).ready(function(){ $('body').addClass('js'); var current = null; $('h2').click(function(e){ if(current){ current.removeClass('current'); } current = $(this).next().addClass('current'); }) });

By adding the class js to the body of the document and toggling the class current for the current section, you maintain control of the look and feel in CSS:

<style type="text/css" media="screen"> .section{ border:1px solid #999; background:#ccc; } .js .section{ display:none; } .js .current{ display:block; border:1px solid #999; background:#ffc; } </style>

The beauty of this is that the handle will be re-usable by the CSS designer and maintainer. Anything without the .js selector would be the non-scripting-enabled version of a part of the document, and anything with the .js selector is applied only when JavaScript is available. And yes, you should think about the case when it is not.

Sin #4: Depending On JavaScript And Certain Input Devices

There is quite a discussion about the need to consider non-JavaScript environments in this day and age, but here is a fact: JavaScript can be turned off, and any JavaScript could break the page for the other scripts that are included. Given the flakiness of code out there that may be running alongside yours and the instability of wireless and mobile connections, I for one want to build one thing: code that works.

So, making sure that the most basic usage of your product does not depend on JavaScript is not just nice to have but essential if you expect people to actually use the product.

Absolutely nothing is wrong with using JavaScript heavily. On the contrary, it makes the Web much smoother and saves us a lot of time if done right. But you should never promise functionality that doesn't work. And if you rely on JavaScript, this is exactly what you're doing. I've already covered the effects of bad JavaScript in detail in the AJAX, JavaScript testing and security articles here on Smashing Magazine, but once again here are some simple steps you can take to make sure you don't break your promise to end users:

Anything vital to the functionality of your product should not require JavaScript. Forms, links and server-side validation and re-direct scripts are your friends.

If something depends on JavaScript, build it with JavaScript and add it to the document using the DOM or the equivalent method in your library of choice.

If you add JavaScript functionality, make sure it works with the keyboard and mouse. Click and submit handlers are bullet-proof, whereas key and mouse events are flaky and don't work on mobile devices.

By writing clever back-end code that recognizes when data is required by JavaScript rather than building APIs that render HTML, you avoid having to do double-maintenance, which is an argument that many of the "Everyone enables JavaScript" zealots bring up a lot. For proof of this, check out the presentation on building Web applications using YQL and YUI that I gave a few weeks ago (video in English and German).

When JavaScript Dependence Is Okay (to a Degree)

A lot of misunderstanding about JavaScript dependence stems from people making blanket statements based on the environments they work in.

If you are a Google engineer working on Gmail, you would be hard pressed to think of why you would even bother working without JavaScript. The same goes for widget developers who work on OpenSocial widgets, mobile applications, Apple widgets and Adobe Air. In other words, if your environment already depends on JavaScript, then by all means don't bother with a fall-back.

But do not take these closed environments and edge-case applications as the standard by which we should be measuring JavaScript. JavaScript's greatest power and greatest problem is its versatility. Saying that all websites can stand JavaScript because Gmail needs it is like saying that all cars should have a start button because they work great in Hybrids, or that hybrid cars should have massive tanks and cow catchers because they work great on Hummers. The technical feature set of a product depends on its implementation and target market. Different applications have different base functionality that needs to be satisfied in order to reach the largest audience and not block people out.

Consider the Use Cases and Maintenance

One fascinating aspect of JavaScript-dependent code is that, in many cases, people have simply not considered all the use cases (here's a great example). Take the following HTML:

Without JavaScript, this does nothing whatsoever. There is no sensible action attribute, and the text field has no name attribute. So, even when you send the form off, the server won't get the information that the user has entered.

Using jQuery and a JSON data source such as YQL, you can do a pure JavaScript search with this:

$('#s').click(function(event){ event.preventDefault(); $('<ul/>').appendTo('#results'); var url = $.getJSON('http://query.yahooapis.com/v1/public/yql?'+ 'q=select%20abstract%2Cclickurl%2Cdispurl%2Ctitle%20'+ 'from%20search.web%20where%20query%3D%22'+ $('#search').val() + '%22&format=json&'+ 'callback=?', function(data){ $.each(data.query.results.result, function(i,item){ $('<li><h3><a href="'+item.clickurl+'">'+ item.title+' ('+item.dispurl+')</a></h3><p>'+ (item.abstract || ') +'</p></li>'). appendTo("#results ul"); }); }); });

This works... unless of course you are like me and prefer to send forms by hitting "Enter" rather than clicking the "Submit" button. Unless I tab through the whole form and focus on the "Submit" button, I get nothing.

So, that's the first thing to fix. If you create forms, never use a click handler on the button. Instead, use the submit event of the form. This catches both the clicking "Submit" and hitting "Enter" cases. With one change, you now support all of the keyboard users out there, and the whole change is contained in the first line:

$('#f').submit(function(event){ event.preventDefault(); $('<ul/>').appendTo('#results'); var url = $.getJSON('http://query.yahooapis.com/v1/public/yql?'+ 'q=select%20abstract%2Cclickurl%2Cdispurl%2Ctitle%20'+ 'from%20search.web%20where%20query%3D%22'+ $('#search').val() + '%22&format=json&'+ 'callback=?', function(data){ $.each(data.query.results.result, function(i,item){ $('<li><h3><a href="'+item.clickurl+'">'+ item.title+' ('+item.dispurl+')</a></h3><p>'+ (item.abstract || ') +'</p></li>'). appendTo("#results ul"); }); }); });

We've now covered the first case. But without JavaScript, the form still doesn't do anything. And another problem brings us to the next sin of writing JavaScript.

Sin #5: Making Maintenance Unnecessarily Hard

One thing that keeps great code off the Web is that our work environment, deadlines and hiring practices condition developers to build code for quick release, without considering how difficult maintaining that code will be later on. I once called JavaScript the village bicycle of Web design ( slides here): anyone can go for a ride. Because the code is available in the open, future maintainers will be able to mess around with it and extend it any way they like.

The sad thing is that the harder your code is to maintain, the more errors will be added to it, leading it to look more like alphabet soup than organized script.

Take the above example. Those of you who haven't worked with YQL and JSON-P for cross-domain AJAX undoubtedly had a "What?" moment looking at the code. Furthermore, keeping a lot of HTML in JavaScript easy to follow is hard, and guess what is the first thing to change when a new design for the page comes along? Exactly: the HTML and CSS. So, to make it easier to maintain, I for one would shift all of the work to the back end, thus making the form work without JavaScript and keeping maintenance of all the HTML in the same document:

<?php if(isset($_GET['search'])){ $search = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED); $data = getdata($search); if($data->query->results){ $out = '<ul>'; foreach($data->query->results->result as $r){ $out .= "<li> <h3> <a href="{$r->clickurl}">{$r->title} <span>({$r->dispurl})</span> </a> </h3> <p>{$r->abstract}</p> </li>"; } $out .= '</ul>'; } else { $out = '<h3>Error: could not find any results</h3>'; } } if($_SERVER['HTTP_X_REQUESTED_WITH']!='){ echo $out; die(); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax Search with PHP API</title> <link rel="stylesheet" href="styles.css" type="text/css"> </head> <body> <form action="independent.php" id="f"> <div> <label for="search">Search</label> <input type="text" value="kittens" name="search" id="search"> <input type="submit" id="s" value="Go"> </div> </form> <div id="results"><?php if($out!='){echo $out;}?></div> <script src="jquery.js"></script> <script src="ajaxform.js"></script> </body> </html> <?php function getdata($search){ $url = 'http://query.yahooapis.com/v1/public/yql?'. 'q=select%20abstract%2Cclickurl%2Cdispurl%2Ctitle%20'. 'from%20search.web%20where%20query%3D%22'.$search.'%22'. '&format=json'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $data = json_decode($output); return $data; } ?>

Someone who doesn't understand PHP at all should still be able to change the HTML display without breaking the code. With this in place, the JavaScript boils down to a very simple script:

$('#f').submit(function(event){ event.preventDefault(); $.get('independent.php?search=' + $('#search').val(), function(data) { $('#results').html(data); } ); });

The normal way to make code more maintainable is to move everything that is likely to change away from the main functional part of the script into a configuration object at the very top of the script. You can return this as an object to the outside world to allow people to set it before they initialize the main functionality.

So, one change we can make to our earlier example-albeit a small one now, but that can change quickly when more requirements come in-is to have a configuration section right up front that defines the CSS classes in use:

$(document).ready(function(){ /* Configuration object - change classes, IDs and string here */ var config = { /* CSS classes that get applied dynamically */ javascriptenabled:'js', currentsection:'current' } /* functionality starts here */ $('body').addClass(config.javascriptenabled); var current = null; $('h2').click(function(e){ if(current){ current.removeClass(config.currentsection); } current = $(this).next().addClass(config.currentsection); }) });

For more information on configuration objects and why they rock for maintenance, check out the blog post " Providing Script Configuration Inline and Programatically ".

In summary, go over your code once more when you think you've finished with it and the next person is about to take it over.

Sin #6: Not Documenting Your Code

"Good code documents itself" is a terribly common and misguided belief. In my years as a developer, I've found that my style of coding has changed constantly. What was common knowledge and best practice in 2004 might be forgotten or even considered poor style these days.

Documenting all of the tricks and workarounds we do to make our code work in different browsers is definitely a good idea. This allows future maintainers to remove them when the targeted browser version becomes obsolete or a library function fixes the issue.

Commenting your code also allows the maintainer to trace it back to you should they need some piece of information, and it allows people who have stumbled across your script to include it in a larger solution or library (which has happened to me). Because JavaScripts tend replicate on the Web (in all of those blogs and "script collections"), it is also a way to make your name known.

Don't go overboard with commenting, though. Obvious things don't need to be spelled out. I have found the following situations worthy of comment:

Necessary hacks. Browser hacks; content clean-up; things that should be supported server-side but are not yet.

Sections that are likely to change. Timely solutions; IDs, classes and strings (as explained earlier).

Start of classes and reusable functions. With name, author, version, date and license.

Third-party code. Give credit where credit is due.

Sections with dependencies. Some comment like, "Needs the Google API with an own key-this one will not work on your server."

In short, comment on anything that deviates from the normal flow of coding. I tend to use /* */ instead of // because it won't create a bug if people remove the line break by accident.

One special case is commenting out sections that will be necessary in future releases or that depend on functionality not currently available. This can be amazingly useful but also a security risk, depending on what you're commenting out. For example, don't leave in any code that points to server-side APIs that are not available yet but could at any time be half-implemented. I've seen this before, where administrator links with the full unprotected path were commented out in the HTML.

Still, commenting out can be very useful for debugging. One neat trick is the following:

/* myFunction('do something'); // */

This is now commented out. But by adding a single slash in front of the first comment line, you will uncomment the whole block and make it live.

//* myFunction('do something'); // */

This trick makes it awfully easy to toggle whole blocks.

Sin #7: Optimizing For Machines, Not People

The last sin is over-optimizing JavaScript based on the scads of information about performance that are available to us. You will find a lot of information on the Web about optimizing JavaScript for performance in the current browser environment. Notice that "current browser environment"-much information is browser- and version-specific and a necessary evil for now, but not necessarily in future. If your application is large or your website is high traffic, knowing and applying this information could make or break it. Again, though, a lot of this applies to edge cases that would have little impact on small projects and environments. This optimization does make it harder to maintain the code; some of the things we need to do to make browsers run fast on high-scale websites, such as writing out script nodes with document.write(), are downright nasty.

When faced with the choice between making code cleaner and easier to amend, extend and understand on the one hand, and shaving two milliseconds off every page load on the other, I opt for the former. A lot of JavaScript optimization can be done through scripts. And rather than teach all developers on a project the ins and outs of JavaScript performance, an expert team (or even a tool) could optimize the code before it goes live.

If you can do anything with machines to make the jobs of other machines easier, do it. The time has come for us to apply build processes as much to front-end code as we do to back-end code, instead of forcing ourselves to follow coding practices that go against the natural flow of writing code.

Further Reading

I hope you've gotten an idea now of how to make scripts more useful, easier to extend and safer to use. For more information, please check out the following links:

# data[].attributes.attachment_link.title
The Seven Deadly Sins Of JavaScript Implementation

# data[].attributes.attachment_link.description
Using JavaScript has become increasingly easy over the last few years. Whereas back in the day we needed to know the quirks of every browser, now many libraries such as jQuery, YUI, Dojo and MooTools allow someone who doesn't even know JavaScript to spruce up boring HTML documents with impressive and shiny effects.

# data[].attributes.body
Look from 'Performance Issues' onwards...

# data[].attributes.attachment_link.description
So that's JavaScript. Simple huh? Maybe not so simple, but this article should at least give you a start, and some ideas on how to tackle the JavaScript-related problems you will come across.

# data[].attributes.body
Some JavaScript needs different language in different browsers

Language not working in browser

// works in all browsers:
var a = [1, 2, 3]
// works in all browsers but IE
var b = [1, 2, 3,]

# data[].attributes.attachment_link.readable_text
The short answer is every browser writes it's own interpreter for JS
The long answer
To understand why a programming language functions differently you have to understand what happens to a programming language at execution. First there are two types of languages interpreted and compiled. Compiled languages are turned from people readable "code" to machine code before execution and distributed as a binary.

Interpreted languages are compiled on the fly, JS is one of those languages. What does it mean to compile a language on the fly? Well, a computer can understand nothing but 1's and 0's and because of this all higher level languages must be broken down to instructions and then binary. When something is compiled on the fly it compiles a line, then runs it, then compiles the next. (of course there are intricacies but that really is the short of it)

Because JS really has never had a stand alone interpreter until recently, and the browser is JS's main purpose every company had to write their own interpreter that would go into their browser. Microsoft, Mozilla, Netscape... Everyone needed to think of how certain things could be handled and then execute them.

Because of this two things happen first, you are never gonna get the same thing if two people are working on it. Think about when you take an intro to Comp Sci course everyone has to make a calculator app but everyone takes a different approach. That happens all the time with js, and causes some browsers to crawl while others fly.

The second is that companies get set in their ways, they have too much time and energy invested in their interpreter and don't want to start over when modifying works and is cheaper. This means that differences that arose in the past when JS was less used and no where near as critical to web development will remain just because it's really difficult to roll out a whole new version of IE with webkit when it has been centered around it's own interpreter for years.

# data[].attributes.attachment_link.title
How is it that Javascript can function differently from browser to browser?

# data[].attributes.attachment_link.description
The short answer is every browser writes it's own interpreter for JS The long answer To understand why a programming language functions differently you have to understand what happens to a programming language at execution. First there are two types of languages interpreted and compiled.

# data[].attributes.body
mentions read/write

# data[].attributes.attachment_link.description
JavaScript has its own security model, but this is not designed to protect the Web site owner or the data passed between the browser and the server. The security model is designed to protect the user from malicious Web sites, and as a result, it enforces strict limits on what the page author is allowed to do.

# data[].attributes.headline
DOM means the order that HTML is unpacked. Usually unpacks in the same order that you would 'indent'

# data[].attributes.subject
DOM means the order that HTML is unpacked. Usually unpacks in the same order that you would 'indent'