JavaScript Strict Mode Explained

JavaScript is everywhere. It’s run in web sites, as utilities on many operating systems, and in any host, like IE, Firefox, or Chrome and it’s a first class citizen in Windows 8 Metro style app development. Since JavaScript has been around for a long time, it still has a lot of baggage from when it was immature. Because of this, Strict Mode has become a feature in ECMAScript 5, or ES5 (JavaScript).

What is Strict Mode and why use it?

Because Strict Mode is ECMAScript, it is a standard, and a best practice, and highly recommended that you use it. In the future, Strict Mode will be your only choice, which is certainly for the best. Strict Mode offers up these enhancements to the JavaScript language:

  • JavaScript throws errors if you try to use deprecated language elements
  • Variable declaration is mandatory
  • Disallows duplicate property and parameter names
  • The eval() method is safer to use, but still considered evil in some cases.
  • Deprecates the with statement
  • JavaScript throws errors if you try to assign a value to a read only property
  • Decreases the global namespace pollution

Most ES5 compliant JavaScript runtimes support Strict Mode, and you can get full details at this in-depth article on Strict Mode at MSDN.

Where can I use Strict Mode?

You can use strict mode in any JavaScript host or engine that supports ES5 standards, and specifically, Strict Mode. Check out this comprehensive ES5 Compat Table on Github to see if your browser supports strict. You will see a lot of green lights, so there is wide support across browsers. This means if you are a web developer you can start using Strict Mode today.

If you are a Windows 8 Metro style apps HTML/JS developer, Strict Mode is automatically added to the project templates in Visual Studio 11 as WinJS supports Strict Mode.

Enabling Strict Mode

Applying Strict Mode is very easy to do. Just add the “use strict” directive to your code (it’s a string literal so include the quotes). The physical location of the strict directive determines the scope of Strict Mode. Below is a table showing the relationship between Strict Mode and scope. This means you can turn Strict Mode on and off granularly in code.

Code location Scope
Beginning of any .js file Global
Beginning of the script inside a <script> element. <script> element
Preceding function block
First line in function block
Function

As you can see, Strict Mode is flexible but try to keep Strict Mode out of a global setting where possible when dealing with Web pages (HTML, ASP.NET, PHP, etc…). If other scripts include your script using Strict Mode, then Strict Mode could apply to the included scripts and that can create problems. However, you can get the same effect as global Strict mode by wrapping your code like so:

$(function () {
    “use strict”;
    function strictFoo() {
        alert(“I am in strict mode”);
    }
    function strictFoo2() {
        alert(“Me too!”);
    }
});

This creates a block around both functions and Strict Mode appears global to to the all code that exists in that block, essentially making strict container for that code. 

Summary

Strict Mode is great because it catches common programming ID10T errors. These are the kind of errors everyone makes, regardless of experience, and often because of experience. It’s very easy, especially when moving from a compiled language, to miss some of the finer nuances of JavaScript. Strict Mode helps smooth out those JS language kinks.

Create mobile site layouts with CSS Media Queries

Web sites and apps need to deal with the challenge of serving content to a multitude of browsers and devices. People access web sites and apps via tablets and mobile phones more than ever before, and smart phone usage numbers are growing exponentially. In some populations, mobile Web traffic is higher than traffic from desktops. Technology nowadays means devices and machines range in size from quite small to quite big, and as a result, you the developer must format the content appropriately for each device type. You can accomplish this task by using CSS Media Queries, as they are the best foundation of a responsive UI.

What is a CSS Media Query?

In the past, in order to serve browser or device specific content, we would write code that determines which style sheet to use based on feature detection (or UA detection on older Web sites). Now, instead of having to write code, we can use declarative CSS Media Queries to apply rules to an HTML page based on the requesting device’s characteristics. CSS Media Queries are a way to apply different styles when the requesting browser or device matches the conditions within the media query. With media queries you can target various screen sizes, orientations, and form factors including TV and print, and serve tailored content to them. For example, the media queries below apply a different layout to the tablet sized, landscape screen (768 x 1366 ), vs. the phone sized, portrait screen (320 x 480):

@media screen and (min-width: 768px) and (orientation: landscape)

{
    /* CSS layout for screens with minimum 800px width, landscape */

} @media screen and (max-width: 320px) and (orientation: portrait)

{
    /* CSS layout for screens with maximum 320px width, portrait */
}

While multiple media queries can exist side by side in a single .css file (like the example above), maintenance can be easier if you create one .css file for each type of device you want to support. Doing so allows you to swap style sheets based on the media query defined in the media attribute of the <link> tag.

<link rel=”stylesheet” type=”text/css” href=”smartphones.css” media=”only screen and (max-device-width: 320px)” /> <link rel=”stylesheet” type=”text/css” href=”tablets.css” media

="screen and (min-device-width: 800px)" />

Effectively, media queries rid you of the long lines of “if then” statements otherwise required as conditional logic to figure which style sheet to use for which occasion. You no longer need to resort to using JavaScript to swap style sheets by querying user agents, media types or common device form factors.

Design a page layout with CSS Media Queries

Layouts that fit traditional landscape screens work horribly on smart phones, and thus the need for a responsive layout. A responsive layout is fluid and adaptable, and needs flexible elements such as grids and images that can automatically resize based on the form factor of the requesting device. In addition to resizing elements, you must adapt the page to remove content or unnecessary navigation, because space is at such a premium on small devices.

CSS Media Queries are the foundation of responsive layouts that work across devices. Let’s start with an example of a simple web page with a two column layout in which there is a container <div> and two child <div> tags that render the columns. This layout is for desktop browsers, and later we’ll modify it to run on a phone.

#wrapper 

{ margin:0 auto; height:768px; } #sidebar { background-color:#2885c9; width:24%; height:600px; float:left; } #content { background-color:#229731; width:75%; height:600px; float:right

;
}

<!DOCTYPE html> <html xmlns=”http://www.w3.org/1999/xhtml”> <head> <title>CSS Media Queries</title> <link href=”default.css” rel=”stylesheet” /> </head> <body> <div id=”wrapper”> <div id=”sidebar”><span>Side bar</span></div> <div id=”content”><span>Content goes here.</span></div> </div> </body> </html>

The code above looks like this in IE 10, a desktop browser. There is a column to the left (side bar) and one on the right (content).

 

image_thumb3_2

Of course, this layout just won’t work in a small, portrait, screen. Most side bars are for navigation, that when mobilized is painful to use in such a small form. Repositioning the elements so that the side bar is on top of the content is a much better layout for smart phones, because of the change in orientation. We can do this by creating a media query and modifying the CSS to fit smart phone dimensions. Below is a media query definition containing the same three selectors in the previous sample, but modified for a smart phone layout. What was the leftmost column (the side bar) is now positioned at row #1, and its adjacent content area is now positioned at row #2. As you might expect, the sizes of the elements are smaller than in the desktop version.

@media screen and (max-width: 320px) and (orientation: portrait) { #wrapper { width:320px; height:480px; margin: 0 0 0 5px; } #sidebar { width:320px; height:90px; float:left; margin: 0 0 5px 0; } #content { width:320px; height:380px; float:left

;
    }
}

 

image_thumb2_2SNAGHTML103a6a17_thumb1_2

The media query works great in IE10 desktop when resized to smart phone dimensions (left side, above image). However, in some phones or emulators, the above media query does not work (right side, above image). This is because we are missing a key component in mobilizing content – the <viewport> meta.

Mobilizing sites with the viewport meta

When mobile devices receive content formatted for the desktop or larger sized browsers, their default action is to zoom out to show all the content. The phone browser tries to show the page as a desktop browser does but condensed into its tiny, portrait, view. They do this for backward compatibility of the many non-mobilized sites that phones otherwise render incorrectly and break. We can change this behavior and tell phones to optimize their default zoom for mobile by using the viewport meta element. The viewport meta instructs mobile devices to resize the content to fit on their screen or to a certain scale based on the tag’s attribute values. Below is an all-purpose viewport that resizes content to fit the device:

<meta name=“viewport” content=“width=device-width”/>

If you aren’t sure what attributes to use, use the above as the default, as it renders the page to fit the device. Now because the phone will render the content correctly, and the output looks like the following:

SNAGHTML9843bc_thumb1_thumb

Notice the browser has applied the media query this time. This is because the phone’s browser took a cue from the viewport and rendered the page like a mobile browser rather than a desktop browser.

Summary

As you can see, CSS Media Queries are the best way to deliver perfectly fitted content to any device, with less maintenance hassles. Media queries aren’t just for the Web either – you can write Windows Store apps in HTML/CSS/JavaScript and use media queries for Windows 8 features like Snap-View. If you are working cross platform, don’t worry about support as CSS Media Queries have a wide adoption across desktop and mobile browsers.

Lastly, if you would like to go mobile but must support the older-than-dirt browsers like IE8 and below then check out Respond.js. Respond is a polyfill for CSS Media Queries (a mechanism for backwards compatibility), enabling their use in old or unpopular browsers.