Things you may not know about Webkit based Dev Tools

I am sure many of you who are reading this article deal with Webkit based dev tools (Chrome / Safari) or Firebug to implement and debug web applications. However there are several cool features in webkit based developer tools (specially Chrome) which are really handy and super quick to use. Knowing all of them will definitely save lot of time for every web based developer.

 

Elements panel drag and drop

You can drag and drop dom elements in the Elements panel. It will enable quick and craze experiments which you can do on the fly. 

 

Undo and Redo

If you ever mistakenly delete any dom element or style property, now they can be claimed back by Undo or Redo feature in dev tools. Do undo or redo the same way you do in your favorite editor, it works the same way (Ctrl+Z / Ctrl+Shift+Z) in Chrome Dev tools now.

 

Open source (Ctrl+O)

Go to sources tab and press Ctrl+O. It will show you list of all available external source files. You can refine the list by typing the part of the name of the file.

 

Open member (Ctrl+Shft+O)

In the sources tab, in the currently opened file, pressing Ctrl+Shift+O gets you list of available functions/methods or css declarations (in case of css file). You can jump to any of them very quickly by typing the name of the method.

 

Console API ($0 – $4)

Select any element in elements panel and write $0 in the console. It holds the latest selected dom element in the elements panel. You can further play with the dom element held in $0 by using any of the JS method on it. $0 comes from console api which is supported by chrome dev tools and firebug. So, your latest 5 different elements selected will be automatically stored in $0 to $4 where $0 points to the most recently selected one. Really handy to experiment with dom elements.

 

Conditional breakpoint

You can have conditional breakpoints in Javscript which will enable execution to pause only when the specified condition is met. For example checking if an element is null or not in a given loop, just set the breakpoint with the condition !element. It will pause only when specified element is not available.
You can have conditional breakpoint by right clicking on already present breakpoint and selecting “Edit Breakpoint” or add a new breakpoint by right clicking on the breakpoint bar and select “Add conditional breakpoint”.

 

Pseudo class inspector

Too irritating to inspect and edit “hover” pseudo class because it doesn’t stay there by the time you move your mouse out of the element. Now you can force dev tools to show classes for the states from (Hover, Selected, Active, Focus) of the DOM element. Just click on the arrow (second right buttom from top right corner in styles pane). You can specify which state you want to see the element in. If you say hover, it will show the element in hover state along with showing styles being applicable to the element in that state. You can easily inspect and edit them.

 

querySelector shortcut ($$ and $)

$$ is the shorthand of document.querySelectorAll (method in New DOM API) which is available in almost all recent browser now. It accepts a css selector in string format and returns list of matching dom Element. Thus $$(“li.item[canBeListed]“) will return list of the list elements which have class “item” on them and have an attribute named “canBeListed” (whatever value) on them. 
$ is the shorthand for document.getElementById. It takes id of element in string format and returns the element with the given id. Thus $(‘categories’) will return the element which has id as “categories”.

 

Multiline console

Shift does the trick. If you press Enter while keeping the shift pressed, it lets you write multiline script in consoles panel.

 

Prettify

If you are unable to understand methods available in a minified javascript file, or want to put a breakpoint at line XY of method ABC, you can do that now by using prettify feature in dev tools. By pressing this little button, your currently opened file in scripts tab, becomes clean, indented code just like regular source code. Now you can put breakpoints the minified JS file where ever you want.

 

Break on error/exception

Not sure, which line exactly created the problem and resulted in the error? Press this little button and then run your javascript. It will pause at the code line which will throw the error if run further. In that paused state, you can check whats the problem with that specific code line.

 

Clear console (Ctrl+l / Cmd+K)

Quickly clear your console by Ctrl+l. (Cmd+K or Cmd+l in Mac)

 

Preserve log on navigation

Want to debug what happens on page load? Avoid your console being cleared by page refresh by checking this option in console panel.

 

Dock to right

I personally like this feature which lets me keep the dev tools in the right side of the current page. Very handy if you are working on a big wide screen. You can dock the the right by checking this option. You can enable this feature by going to settings of developer tools and enable it from general tab.

 

Toggle console in any panel

Press ESC in any panel you are in. It toggles console pane in that panel (except when the panel itself if console panel)

 

Search in all scripts (Ctrl+Shift+F / Cmd+Option+F)

Not sure which file defines the given method? Press Ctrl+Shift+F and search in all the available scripts in current page. It runs pretty fast.

Posted in Developer Tools, Front End Development, Javascript | 2 Comments

I spoke at Verchaska

Last week I spoke at Verchaska about performance optimization in Javascript and how to implement cross browser solutions. It was a nice experience knowing about early stage problems which most of the front end developers face. Most of the content from the talk covered Javascript from basics to advanced. Also, I spoke about CSS, how to implement cross browser solutions and some new cool features in ECMA5, HTML5 & CSS3.

Some of the things which I generally find common across all the novice front end engineers is that, in essence to meet sharp deadlines and for ease of use they all tend to use libraries and frameworks. As a result, they miss the basic beauty of the language. Assume it like this. Libraries are a dashboard to control and use the language who sits between you and the main language engine. You can perform all the actions and functions which are available on the dashboard but the problem arises when it comes to perform some action which is not available on the dashboard and you never bothered to look into actual engine to implement the action yourself. The real path of learning should be, first you understand the language and it’s insights, then you can jump into a library/framework which helps you rapid development your stuff.

It was really fun to explain floating concepts, handling closure memory leaks and Javascript identifier resolution from scope chains. How with & catch effect the performance of identifier lookups badly and why you should avoid eval. Evals are generally vulnerable to security problems and also, it doesn’t let the browser take the advantage of compile time optimization. People were totally delighted after knowing about such deep concepts and asked lots of questions.

Very few were aware that instead of making lot of DOM getter methods and filtering the nodes by writing long complex code just because you want nodes matching some particular selector rule, now you can use the new DOM selector api <element>.querySelector or <element>.querySelectorAll to avoid unnecessary filtering of nodes. Also, I explained them why you shouldn’t do DOM manipulations blindly. Reflow and repaints are costly and can significantly impact your web application performance if not taken care of. Use of timers can help your browser restart run away time and restart it’s stack call trace to avoid browser crash.

It was really fun talking to developers there and talking about some of their common code problems. And, I also learnt a lot while explaining the stuff to them. I really thank Verchaska for inviting me :-)
Posted in Uncategorized | 1 Comment

Cross browser Console augmentation with debug switch

Many times I need to write debug statements in my web application. These statements can be consoles or alerts depending on browser compatibility. Problem is that some browsers support logging, some don’t and others support logging by use of extension. Few differences:

  1. Firefox supports logging using window.console.log after installing Firebug. If firebug is not installed, console statements break the application.
  2. There is no console logging support in Internet Explorer.
  3. Chrome and Safari have native support for logging using window.console.log
  4. Opera supports logging using window.opera.postError.

Besides the differences, whenever I move my code to production I need to remove/comment all debug statements because they might break the application at user’s computer if proper debug statements are not supported by their browsers. I checked all the debug support in major browsers and came up with this script which resolves above issues.

//Call this function after body load
function manageDebug(){
  var debug = false;
  if(window.console) {
    var consoleBackUp = window.console.log;
    window.console.log = function(str) {
      if(debug) {
        consoleBackUp.call(this,str);
      }
    }
  } else {
    var log = window.opera ? window.opera.postError : alert;
    window.console = {};
    window.console.log = function(str) {
      if(debug) {
        log(str);
      }
    }
  }
} //manageDebug ends

manageDebug();
console.log("This works!");

Few advantages:

  • This script will enable you to write debug statements in your code without thinking about their cross browser compatibility. You can use console.log() in any browser.
  • You don’t need to remove them before moving to production. Just disable the debug flag (debug = false) and it takes care. [Make sure that you don't add too many consoles to contribute to size of the file.]

You need to call manageDebug after body load because it needs to check against window.console. Above script has been tested on Firefox, Chrome, Safari, Opera and Internet Explorer. Hope it helps you to decrease your debugging time!

Posted in Uncategorized | Tagged , , | 7 Comments

Create once callable functions

Another use of Javascript closures. You can create functions which are callable only once.

function createChance() {
  var chanceLeft = true;
  return function() {
    if (chanceLeft) {
      console.log("This was the only chance you had.");
      chanceLeft = false;
    } else {
      console.log('Sorry: you already used your chance');
    }
  };
}

var chance = createChance();
chance();
// This was the only chance you had.
chance();
// Sorry: you already used your chance

These kind of functions can be useful when you need to implement security pattern in Javascript. Once created function should be used only once. To call it again you need to request its creation again. Another version of this kind of patters can be to implement envelops, where an envelop can be opened only by the person who has the key to open it.

Posted in Uncategorized | Tagged | 3 Comments

Understanding Google Chrome developer tools

 

This is a very nice presentation given by Chrome team at Google I/O 2010. I got to know so many hidden facts about Chrome Developer Tool and I guess now I need to spend a lot less time in debugging and optimization. Must view for any Front-end developer.

Few of the features which excited me:

  1. Ability to see all the event handlers applied to an HTML element. (Not in firebug)
  2. Ability to see all the prototype chains followed by an HTML element. (Not in firebug)
  3. Real time HTML and CSS editing (This was not there few months back and this is the main reason why I was not shifting to Chrome Developer Tools as my default debugger).
  4. You can edit JAVASCRIPTS TOO at real time! My favorite. (Not in firebug)
  5. Very good tools for profiling and optimization work. Specially – CPU Profile, Heap Profile and Audits.
  6. Firebug command line API support (http://getfirebug.com/wiki/index.php/Command_Line_API)
Posted in Uncategorized | Tagged , | Leave a comment

Object masquerading with Javascript

Often people follow this common approach to make their Javascript programs object oriented. Let me explain one more approach for creating subclasses.

Prototype Approach (Common)

Base Class

function Person(fname, lname){
this.fname = fname;
this.lname = lname;
}

Person.prototype.getFullName = function(){
return this.fname+” “+this.lname;
}

SubClass

function Employee(jobType){
this.jobType = jobType;
}

Employee.prototype = new Person();

Employee.prototype.getNameAndJobType = function(){
return this.fname+” “+this.lname+” “+this.jobType;
}
Continue reading

Posted in Uncategorized | Tagged | 2 Comments

Node.js explained

Node.js has been making a lot of noice from last few months. Finally I decided to check what is it and why is it going so much popular. After digging into it and reading a lot about it, I can say that I should have explored it long back. Its interesting. Author Ryan Dahl has done a fantastic job. Let me explain you more about Node.js.

What is Node.js

 Node.js is a Javascript library which lets you run your Javascript code at server side. Its a powerful library which provides extra set of features through Node.js API. Unlike other Javascript libraries like jQuery or YUI, Node.js is not meant to provide you easy DOM manipulation and rich GUI. Its a library which is meant to let you execute your Javascript code in server side environment. Execution uses event based model instead of thread based model. Using Node.js you can write network applications which are scalable and better in terms of performance.

Continue reading

Posted in Uncategorized | Tagged , | 2 Comments

XHTML1.0 Attributes: Black Widow Web Design

XHTML1.0 Element Attributes by DTD

If you do spot any errors, please send them to info@blackwidows.co.uk.

There does still seem to be some confusion as to whether the target attribute is available within the XHTML Transitional DTD or not.

The current XHTML Transitional DTD at http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd does contain the target attribute (check line 650).

However,the supporting documentation at:

http://www.w3.org/TR/1999/xhtml-modularization-19990406/DTD/doc/xhtml1-t.elt.html

does not list target as an available attribute for the element.

Continue reading

Posted in Uncategorized | Leave a comment

Best Practices for Speeding Up Your Web Site

Best Practices for Speeding Up Your Web Site

The Exceptional Performance team has identified a number of best practices for making web pages fast. The list includes 35 best practices divided into 7 categories.

Filter by category:

  • Content
  • Server
  • Cookie
  • CSS
  • JavaScript
  • Images
  • Mobile
  • All

Continue reading

Posted in Uncategorized | Tagged | 1 Comment

Dynamic script loading in IE

For past few days I was trying to load an external Javascript file dynamically in my web page. It was working fine in FF but strangely wasn’t working in IE. Finally got the crack. Thought of sharing it here.

Consider the given code piece.

var script = document.createElement('script');
script.src = "http://code.jquery.com/jquery-1.4.2.min.js";
script.onload = function(){
alert($(document).length);
};
document.getElementsByTagName('head')[0].appendChild(script);

You make a script tag. Set its source to latest version of jQuery file. Then try to use jQuey. In FF this code will work fine. But in Internet Explorer, you will notive that execution doesn’t go inside the onload function, even after script is loaded. Here is how you need to do it in IE. Continue reading

Posted in Uncategorized | Tagged | 1 Comment