Tuesday, October 27, 2015

Chrome Devtools Tips & Tricks

Chrome Devtools Tips & Tricks

Lately I've spent more time than usual using the Chrome Developer Tools. Along the way I found a couple of nice features that I had previously missed (or at least hadn't needed enough to look for; e.g. blackboxing and asynchronous stacktraces). Because of this, I wanted to summarized a few of the features that I really like about devtools.

1) The little magnifier glass icon that shows you which CSS class/selector in what CSS file that ultimately decides the styling for a specific element and CSS property. For example, select "inspect" on any DOM element and then switch to the "Computed" sub-tab to the right. Find the CSS property you're interested in and clicking the magnifier icon takes you straight to the correct CSS class/selector in the right .css file (very useful when you start out working on a new large web app):

Chrome Devtools Tips & Tricks

2) To see what XHRs the web app sends while you're using it, check the "Log XMLHttpRequests" checkbox under "Settings" and keep an eye on the console tab. Before I knew about this, I would set up my browser to go through an HTTP intercept proxy like Burp suite but this more convenient if you just want an quick overview. Of course, with an intercept proxy you also get the opportunity to modify the XHRs before they reach the server, which is really nice for security testing. A lightweight alternative to that is to look under "Sources :: XHR Breakpoints" and activate the "Any XHR" breakpoint.

Chrome Devtools Tips & Tricks

3) Now, suppose that the web app you're working on is making some XHR at a regular interval (for example, keeping the current view up to date) and you would like to know where this timer is setup (i.e. where the call to setTimeout() or possibly setInterval() is made). To figure this out, you switch to the "Sources" tab, and check the "Async" checkbox. This will make all your stacktraces continue beyond setTimeout() and friends, even multiple levels deep. It does the same thing for requestAnimationFrame() and addEventListener() and a few others too. You'll find the checkbox here:

Chrome Devtools Tips & Tricks

4) To quickly find the code that runs when you click a particular button or link is clicked, activate an "Event listener breakpoint" for Mouse :: Click just before you click the particular button (another killer feature when starting out work on an existing large web app):

Chrome Devtools Tips & Tricks

5) When you use "Event listener breakpoint :: Mouse :: Click" you might end up in a third-party library like jQuery at first, and so you'd have to step a few times in the debugger to arrive at the "real" event handler. A great way to avoid this is to "blackbox" the third-party script. The debugger will never stop inside a blackboxed script, instead it continues to run until it reaches a line that isn't in a blackboxed file. You can blackbox a script by right clicking the filename of the third-party library in the callstack and the selecting "Blackbox Script" from the context menu:

Chrome Devtools Tips & Tricks

6) You can jump to a specific file, by name, using ctrl-p (just like in atom):

Chrome Devtools Tips & Tricks

7) You can jump to a function, by name (but only in the currently open file), using ctrl-shift-p:

Chrome Devtools Tips & Tricks

8) You can search through all files using ctrl-shift-f:

Chrome Devtools Tips & Tricks

9) You can edit using multiple simultaneous cursors by selecting some word and then pressing ctrl-d a few times to select more instances of that word (again, just like in atom). Very nice for renaming variables:

Chrome Devtools Tips & Tricks

10) When working on a website stored locally it's possible to edit files in devtools and save the changes directly to disk. To do this, switch to the Sources tab, right click on the Sources sub-tab and select "Add Folder to Workspace" and then finally select the local folder where your project is located. After that, right click the local copy of some file in your site and select "Map to Network Resource..." and then select the corresponding "network" file:

Chrome Devtools Tips & Tricks

Other handy tips include:

  • $0 in console is the element you selected in the elements view.
  • You can evaluate XPath expressions using $x("//p") (very useful if you're writing selenium testcases and CSS selectors doesn't get you all the way).

I also recommend that you install two Chrome extensions:

  • JSONView will indent and syntax highlight JSON blobs for you (and even allow you to expand/collapse blocks). It also makes URLs inside JSON clickable which often makes it possible to explore a JSON-based API via the browser. For example, try navigating to http://omahaproxy.appspot.com/all.json before and after you install it (better formatting) and also https://api.github.com/ (clickable URLs make it easier to explore the API).
  • JS Error Notifier (non-"spyware" version) creates a popup each time a Javascript error is printed to the console. Unfortunately, the main version of this extension submits private “usage data” to a third-party service (see discussion in issue #28). But at any rate, this extension has helped me notice and fix several bugs.

All in all I really like devtools, the only annoying thing that I can think of is that you cannot customize keybindings:


Thursday, October 22, 2015

The Art of Debugging

The Art of Debugging

Before we start though...

How to skip to the end...
Don't.

Write.

Bugs.

Monday, October 19, 2015

Diamond grid layout with Sass

Diamond grid layout with Sass

Since I started my career on the web, I've been building websites that follow standard grid layouts. It got to a point where I was telling an intern at my company that developers think in rectangles. I mean, there's nothing wrong with rectangular layouts. They're like your mom's Volvo, steady and reliable. But sometimes, it's fun to try something different. I'm lucky enough to work with some awesome designers, and for a new project, they came up with a diamond-based grid layout. Well then, challenge accepted. (•̀o•́)ง

Tuesday, October 13, 2015

Async/Await: The Hero JavaScript Deserved

Async/Await: The Hero JavaScript Deserved

Writing asynchronous code is hard. When it comes to JavaScript we rely heavily on callback functions to accomplish asynchronous tasks which can be unintuitive. This cognitive overhead creates a barrier to entry for newcomers to programming and the language and even causes frequent heartburn for those of us who have been using the language a while.

Tuesday, October 06, 2015

Responsive Images for Busy People: Srcset & Sizes

Responsive Images

This guide won't regale you with the cool theory behind responsive images, because for now, you're just testing the waters. It won't lecture you on the potential benefits to site speed, because there are better resources out there. And it won't dwell on the pitfalls, quirks, or brain-bending complexities of the modern implementation, because you're a busy person and will study these later.

Instead, we're going to look at a single real-life example of efficient image scaling using the new srcset and sizes attributes. These should not be used for art direction – for this, you'll want to use picture and source media. Instead, we're strictly concerned with ensuring that the user's browser loads the most appropriately-sized version of our image based on the size of the viewport. We want the browser to be able to pick a source file before parsing or rendering CSS and JavaScript. To do this, we'll need to supply it with:

  • a list of image source files, plus their widths in pixels/li>
  • hints about the size at which the image will be rendered on the page

A Live Example

We'll dive right in with a live example, and then break down how it works. For the sake of being topical (and because NASA / JPL kindly release their images into the public domain), we'll go with the Curiosity Rover's selfie on Mars. The three image source files have been watermarked for convenience. Take a peek at the HTML and CSS powering this example. What's going on here? The first thing to note is that the usual src and alt attributes are present and correct. Browsers which don't support the new syntax will simply load the resource specified in the src as a fallback.

See the Pen Responsive Images with srcset and sizes by Tom Bennet (@tombennet) on CodePen.

srcset

Next up, srcset. As you'll see, this attribute contains a comma-separated list of image URLs; each one is followed by its width in pixels, specified using the w descriptor. "Why can't we specify heights too?", I hear you ask. Well, most images in responsive environments are constrained by their widths, not their heights, so dealing solely in widths keeps things simple. This situation may change in the future, but not today. So, our browser now knows which resources it can choose from. Splendid. There is, however, a problem: the browser doesn't know the size at which the image will be rendered on the page until it has downloaded and parsed all the relevant CSS and JavaScript files. Relaying this information to the browser before it starts processing your page's layout will enable it to start downloading the appropriate image file as soon as possiblw.

sizes

This is where sizes comes into play. This attribute is used to describe the various sizes at which the image will be rendered on the page. Much like srcset, it takes a comma-separated list, but in this case we supply a list of CSS lengths paired with media conditions, which is then followed by a default length. This is easier to understand when you've got a simple example translated into English, so here goes...
sizes="(min-width: 40em) 33.3vw, 100vw"
This says: "If the viewport is wider than 40em, then this image will take up one third of the viewport. Otherwise, it will take up the full-width (100%) of the viewport." We're pairing media conditions with CSS lengths, thereby giving the browser a clue as to the breakpoints it will encounter in the CSS. Note that more than one pair can be provided. The browser will iterate through your list of media conditions until it finds one that matches, and will then use the paired length as the image's rendered width. If none match, it will use the last length in your list (the one without a paired query) as a default. Here's the syntax:
sizes="
[media condition] [length],
[media condition] [length],
[media condition] [length],
[default length]"
Our browser now has all the information it needs to make a decision; it knows the widths of the source files, and the size at which the image will be rendered on our page.

calc

Why, then, is our Martian example slightly more complex? What is calc doing there? On the Red Planet, as on Earth, determining the size of a single element can be complex in a responsive environment. Thankfully, we can include the excellent and widely-supported CSS calc function to describe a relative length as mathematical expression. In our example, we've used calc(66.6vw - 4em) to express the length: "Two thirds of the viewport width, minus 4ems." Sure enough, head into the CSS, and you'll see rules that set our image width at 66.6% with 2em padding on either side.

Final Thoughts

A few pointers for those of you frantically resizing and refreshing the CodePen to try and change the watermark: the spec is fairly flexible, and allows the browser to make decisions based on both your markup and on other relevant factors. These can include the user's connection, preferences, whether or not a larger asset is already cached, and so on. Something to bear in mind. Support for this technique is quickly gaining momentum. As of the launch of OS X El Capitan, a full implementation is available in the current versions of Chrome, Firefox, Safari, and Opera (including mobile versions). As for Microsoft Edge, it's available in version 13, currently in Insider Preview and due to be released soon. For developers who require wider browser support, Picturefill is an excellent polyfill for responsive images. Version 3.0 – a full rewrite of the codebase – will be available imminently. That's all for now. If this quick primer has tickled your fancy, be sure to check out the excellent resources below for a comprehensive introduction. Happy coding!

Resources

Wednesday, September 09, 2015

A Guide to Vanilla Ajax Without jQuery

A Guide to Vanilla Ajax Without jQuery
Short for Asynchronous JavaScript and XML, Ajax is a mechanism for making partial page updates. It enables you to update sections of a page with data that comes from the server, whilst avoiding the need for a full refresh. Making partial updates in this way can be effective in creating fluid user experiences and can decrease the load put on the server.

Tuesday, July 07, 2015

Responsive Typography With Sass Maps

Responsive Typography With Sass Maps
Managing consistent, typographic rhythm isn't easy, but when the type is responsive, things get even more difficult. Fortunately, Sass maps make responsive typography much more manageable.

Writing the code is one thing, but keeping track of font-size values for each breakpoint is another — and the above is for paragraphs alone. Throw in h1 to h6s, each with variable font sizes for each breakpoint, and it gets cumbersome, especially when the type doesn't scale linearly.

Tuesday, July 07, 2015

How to Become a Great JavaScript Developer

JavaScript Developer

When I was growing up, my interests spanned various, seemingly unrelated fields. I loved maths as much as I loved history. I aimed to be a Renaissance man -a polymath-, that excelled at multiple fields. This turned out to be an arduous task and suddenly I faced the danger of being a jack of all trades, master of none.

Wednesday, June 24, 2015

Understanding CSS 3D-Transforms

Understanding CSS 3D-Transforms

3D transforms can be a bit of a mind-boggling concept at first, particularly given that the HTML canvas (your screen) is a 2D space. While most of us understand the most commonly used 3dtransform - transform: translate3d(x, y, z), there are other values that can effect 3D rendering such as rotate, backface-visibibility, perspective and lots more.

Monday, June 15, 2015

Web Design Principles That You Should Know As A Designer

Web Design Principles
Nowadays almost everyone will have a website to promote themselves whether they are a business or freelance worker, some people even make sites to promote their hobbies or interests. With many new websites being added everyday the web is becoming a more crowded and competitive place.

Not everyone has the skills and expertise to know what it takes to create a really successful website, which creates high demand for the services of website designers. Successful website design requires a fine balance of creative talent and technical ability making a it a highly skilled process.