Archive

Archive for the ‘Web Development’ Category

Webdev Weekly #15

April 18th, 2010

Webdev Weekly #15

Webdev Weekly has been on a break for few weeks. From now on, I’m going to post the best links related to web development and design much more often (aka weekly).

This week’s article includes only few, but very good links to strong articles and websites.

General Web Development

Going Lean with Website Production

A good article about Lean Development with production websites.

HTML & CSS

7 Useful CSS3 Code Generators

This article focuses on seven (probably best known) CSS3 code generators.

IE Print Protector

“IE Print Protector is a piece of javascript that allows you to print HTML5 pages in Internet Explorer. “

Javascript, jQuery and Other

jStorage

How to store data locally with JavaScript, the cross-browser way!

Compose: functions as building blocks

“JavaScript treats functions as first class objects, that is they can be created and modified dynamically and passed as data to other functions and objects. Shamelessly continuing this theme, allow me to introduce functional composition…”

Server-Side Development and Frameworks

8 useful code snippets to get started with WordPress 3.0

This post gathers the most useful resources to get you started with WordPress 3.0.

Advanced Regular Expression Tips and Techniques

Some advanced tips for working with regular expressions by Burak Guzel

Top 10 Useful .htaccess rewrites, Mod_Rewrite Tricks and Tips

Like the title says: 10 very useful tips in brief format for all .htaccess freaks.

Security and Hacking

x5s – automated XSS security testing assistant

“x5s is a Fiddler addon which aims to assist penetration testers in finding cross-site scripting vulnerabilities. It’s main goal is to help you identify the hotspots where XSS might occur…”

Author: Samuli Hakoniemi Categories: Web Development Tags:

When jQuery returns “failed” in IE – and how it’s probably resolved

March 21st, 2010

When jQuery returns failed in IE - and how it's probably resolved

In web development, I love facing unexpected problems I haven’t seen before. It’s an excellent situation to learn new things. And the moment right after I’ve found a solution – it’s a perfect moment.

But when I can’t find a solution, no matter how hard I try, and especially when I can’t find anything from Google that could help me.. well, I get very frustrated.

In this brief article, I’ll go through one problematic situation that really got me frustrated. Plus, this hopefully can be found via Google and therefore works as a solution to anyone who’s facing a same problem.

Last week at work, I encountered a very peculiar problem in Internet Explorer. There were several IE-related bugs reported in a certain part of the service. However, I couldn’t reproduce them and I expected these bugs had been fixed during other updates in the code..

..until it suddenly happened. All the tested versions of IE’s (6, 7, 8) started reporting either error “failed” or “unexpected error”, pointing to jQuery’s code. And there worst part was that error occurred occasionally, although nothing was changed.

In this case, there’s jQuery 1.3.2 in use. Error message didn’t help and the line it was pointing to, belonged to a internal / helper function into jQuery.

At first, errors disappeared after some fixes I expected to resolve the situation. But, like I mentioned earlier: these errors were occasional.

I didn’t have anything that could have helped me at least a little on tracking this problem (later I found not even unit tests would’ve solved this – although it’s not an argument why I didn’t have unit testing for javascript). So, my only choice was trying to isolate the problem function by function, line by line.

Ultimately I found that all the errors were caused by event handler bindings made with function $.fn.live(). I couldn’t blame the selectors being too unprecise, although I reduced the amount of troublemakers by fine-tuning them. In addition, I found that wrapping them in setTimeout() with small delay would have possibly fixed the problem. Also, IE6 had the most problems, while IE7 started to feel stable.

Most likely there was something going on with perfomance. However, after all this I wasn’t in a mood to expect these problems were completely solved. So I ended up binding event handlers with $.fn.bind() whenever something was dynamically added. It meant more lines of code, but it also meant that no errors were occurred ever again.

The point of this article can be put in one sentence: if you receive an error with message “failed” or “unexpected error” from jQuery and this happens only in Internet Explorer, comment out every possible live() binding and try again.

Debugging and Testing in Internet Explorer Made Easy

March 5th, 2010

Debugging and Testing in Internet Explorer Made Easy

It’s somewhat usual to leave the testing with Internet Explorer until the end of the project. This is quite acceptable when you’re dealing mainly with layout issues.

But when you’re building a web application with loads of features, there are several issues to struggle with: constant debugging, client-side performance, proprietary bugs and so on. However, getting your hands dirty with IE doesn’t always feel as comfortable as with other browsers.

In this article, I’m going to list and review different set of tools, which will help you and make your debugging and testing process in Internet Explorer much more enjoyable.

This article is a general overview of different tools and resources that are available for IE. Unfortunately it’s not providing any detailed information on how to use these tools properly. But I still hope this article offers you a good start.

This article is split into following topics:

  1. Browser Packages – different IE browser packages
  2. General Debugging Tools – most common debugging tools
  3. Performance Testing Tools – excellent tools for performance testing
  4. Other Resources – additional resources worth of checking

Browser Packages

Browser Packages

The first step is to install all the common versions of Internet Explorer (IE6, IE7, IE8). There are several options available and I’ll review four of them.

Internet Explorer Collection

My personal recommendation is Internet Explorer Collection. Don’t be scared, it’s very reliable (despite the appearance of website). Internet Explorer Collection contains multiple IE versions, which are standalone so they can be used at the same time.

The main reason I recommend this package is because the browsers it provides are very stable. Internet Explorer Collection also includes the Internet Explorer Developer Toolbar.

BrowserSeal.BrowserPack

If you’re in need of older versions of other browsers, I recommend installing BrowserSeal.BrowserPack. It uses the Internet Explorer Collection mentioned above, but in addition it allows to install browsers like Safari 3 and Opera 9.

Browsers provided in BrowserSeal.BrowserPack are very stable and I haven’t encountered any problems.

IETester

IETester contains several advantages compared to other packages, like opening different versions of IE into tabs.

IETester is provided by DebugBar and they’re also responsible for providing excellent debugging tools like DebugBar and Companion.js (both reviewed later in this article).

However, IETester still (v0.4.2) feels quite unstable and I’ve encountered some contradictions while debugging. But I’m quite convinced these kind of issues gets fixed sooner or later and therefore keep IETester in my armament.

Microsoft Expression Web SuperPreview

Microsoft Expression Web SuperPreview is a stand-alone application and part of Microsoft Expression Web 3 product. Mainly, it can be used for viewing the pages side by side on IE6, IE7 and IE8.

In my opinion, this application doesn’t provide any value for debugging and testing. It’s targetted for web design, offering the possibility for swift visual overviews and comparing layouts between different IE versions.

General debugging tools

General Debugging

I’m quite certain you’re using Firebug on Firefox. And maybe you’re aware of Firebug Lite and already using it. Still, there’s a good chance that you’re wondering how to debug in Internet Explorer.

Firebug Lite

You might be already aware of Firebug Lite. If not, read further. Firebug Lite is a JavaScript file you can insert into your pages to simulate some Firebug features in other browser than Firefox. It doesn’t affect or interfere with HTML elements that aren’t created by itself.

I have to say I’m not that big fan of Firebug Lite. First of all, many core features of console are already implemented in other browsers. Second, it’s not always working properly. I’ve personally encountered some problems especially with IE and therefore I never count solely on it.

Still, it’s a must. Go ahead and start using it, if you still haven’t.

IE Developer Toolbar

You may be familiar with Developer Tools for IE8. Well, IE Developer Toolbar is practically the same tool for IE6 and IE7. And it’s provided together with IE Collection by default.

IE Developer Toolbar is easy to use and offers a broad set of options for general debugging. It can be compared to Web Developer add-on for Firefox.

DebugBar

All the features you’re missing from Developer Toolbar, can be found in DebugBar. In most cases, when you need to find something out of the document, this can be done with DebugBar. It’s very fast and reliable.

If I had to describe DebugBar in three words, I would definitely say “it just works!”.

CompanionJS

Companion.js integrates with IE and it can be briefly described as a simplified version of Firebug. Like I mentioned before, I’m not that favor for Firebug Lite on IE, and Companion.js feels much more comfortable for basic-level console logging and error reporting.

However, there are two clear disadvantages in Companion.js: 1) it doesn’t support methods like console.dir() yet, and 2) it causes occasional breakdowns with other development tools for IE.

Performance Testing Tools

Performance Testing

Client-side performance testing and optimization is a practice that hasn’t “existed” very long in Web Development. I mean it hasn’t been getting a lot of attention until recently.

As you might know, Internet Explorer (especially IE6) doesn’t perform as good as many other browsers. I was actually quite surprised when I started testing performance with IE that even very small things can really affect on performance.

I’m reviewing couple of performance testing tools that are also possible to implement in any browser, not just in Internet Explorer.

dynaTrace AJAX

If you’re using Speed Tracer on Google Chrome, then you’re going to love dynaTrace AJAX. Like the name says, it’s meant for diagnosing and tracking AJAX and client-side scripting perfomance issues. But in addition, it offers valid tools for tracking rendering (painting) issues and network load in general.

dynaTrace AJAX isn’t the easiest tool to take in proper use. I was bit troubled on how to demonstrate this tool or prove the capabilities in it. Fortunately, my colleague posted a link to an article, which solved the problem: How to Speed Up sites like vancouver2010.com by more than 50% in 5 minutes.

dynaTrace’s blog contains many more resources how to use this powerful tool. Read them, install dynaTrace AJAX and tackle all those nasty perfomance issues that freezes up your Internet Explorer :)

MySpace’s Perfomance Tracker

I’d say the name of this application is a bit distracting. But MySpace’s Perfomance Tracker, or “msfast” (project home) is a browser plugin that help developers to improve their code performance by capturing and measuring possible bottlenecks on their web pages.

It’s very efficient tool for tracking loading and rendering issues, and in addition, it provides the validation results either in YSlow or MySpace’s own ruleset.

I had some problems when I tried to install Beta. But when I first installed the alpha version and afterwards upgraded it to the beta version, it started working properly.

JSLitmus

JSLitmus is a lightweight tool for creating ad-hoc JavaScript benchmark tests. I really recommend JSLitmus for testing performance of your Javascript in general.

JSLitumus really provides additional value in Internet Explorer. As generally known, there are surprising Javascript issues that really can cause performance hit in Internet Explorer. And by creating even simple testcases, you’ll probably find the actual troublemakers.

Fiddler2

Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic. Fiddler allows you to inspect all HTTP(S) traffic, set breakpoints, and “fiddle” with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language.

To be honest, I haven’t use Fiddler a lot. Mostly because performance issues I’ve encountered related to traffic on website has always been solved with another tool (in another browser). But Fiddler really provides a good and broad insight what’s actually happening between the browser and the server and offers a worthy set for tweaking details.

Other Resources

While writing this article I encountered a tool called IEInspector. It’s chargeable, but there’s a free trial version available. I didn’t have enough time to evaluate it, but you can always give it a try.

There’s also a listing at Microsoft Window’s website called Internet Explorer 8 Readiness Toolkit, which is described as a list of convenient development and test tools to help test and modify applications to run on Internet Explorer 8.

There are probably other tools and resources that I’m probably not aware of. If you know good tools or resources for debugging and testing in Internet Explorer, go ahead and leave a comment.

10 Small Things You May Not Know About Javascript

February 18th, 2010

It doesn’t matter how many years I’ve been dealing with Javascript – it contains many little things that surprises me almost every week. For me, Javascript means a constant learning process.

In this article, I’ll provide ten small Javascript tips, mainly aimed for beginner and intermediate Javascript developers. Hopefully there’s at least one useful tip for every reader :).

1. Variables conversions

This sounds quite obvious, but as far I’ve seen, using object constructors, like Array() or Number() for converting variables is quite common practice.

Always use primitive data types (sometimes referred as literals) for converting variables. These won’t do any extra tricks and they usually have better performance.

var myVar	= "3.14159",
	str		= ""+ myVar,//	to string
	int		= ~~myVar,	//	to integer
	float	= 1*myVar,	//	to float
	bool	= !!myVar,	/*	to boolean - any string with length
							and any number except 0 are true */
	array	= [myVar];	//	to array

Converting to dates (new Date(myVar)) and regular expressions (new RegExp(myVar)) must be done with constructors. However, always use /pattern/flags when creating regular expressions.

2. Converting decimals to hex or octals and vice versa

Are you writing separate functions for hex (or octal) conversios? Stop. This can be easily done with existing methods:

(int).toString(16);	// converts int to hex, eg 12 => "C"
(int).toString(8);	// converts int to octal, eg. 12 => "14"
parseInt(string, 16) // converts hex to int, eg. "FF" => 255
parseInt(string, 8) // converts octal to int, eg. "20" => 16

3. More playing with numbers

In addition to previous section, here are some more small tricks with when dealing with numbers.

0xFF; // Hex declaration, returns 255
020; // Octal declaration, returns 16
1e3; // Exponential, same as 1 * Math.pow(10,3), returns 1000
(1000).toExponential(); // Opposite with previous, returns 1e3
(3.1415).toFixed(3); // Rounding the number, returns "3.142"

4. Javascript Version Detection

Are you aware which version of Javascript your browser supports? If not, check Javascript Versions sheet from Wikipedia.

For some reason, features in Javascript version 1.7 are not widely supported. However, most browsers released within a year support features in version 1.8 (and in 1.8.1).

Note: all the versions of Internet Explorer (8 and older) supports only Javascript version 1.5.

Here’s a tiny script both for detecting the version of Javascript via feature detection. It also allows checking support for specific version of Javascript:

var JS_ver	= [];

(Number.prototype.toFixed)?JS_ver.push("1.5"):false;
([].indexOf && [].forEach)?JS_ver.push("1.6"):false;
((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;
([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;
("".trimLeft)?JS_ver.push("1.8.1"):false;

JS_ver.supports	= function()
{
	if (arguments[0])
		return (!!~this.join().indexOf(arguments[0] +",") +",");
	else
		return (this[this.length-1]);
}

alert("Latest Javascript version supported: "+ JS_ver.supports());
alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));

5. window.name for simple session handling

This one is something I really like. You can assign values as a string for window.name property and it preserves the values until you close the tab or window.

Although I’m not providing any script, I strongly suggest you to take full advantage from it. For instance, it’s very useful for toggling between debugging and (perfomance) testing modes, when building a website or an application.

6. Testing existence of property

This issue can be approached at least from two directions. Either we check whether property exists or we check the type of property. But always avoid these small mistakes:

// BAD: This will cause an error in code when foo is undefined
if (foo) {
	doSomething();
} 

// GOOD: This doesn't cause any errors. However, even when
// foo is set to NULL or false, the condition validates as true
if (typeof foo != "undefined") {
	doSomething();
}

// BETTER: This doesn't cause any errors and in addition
// values NULL or false won't validate as true
if (window.foo) {
	doSomething();
}

However, there may be situations, when we have deeper structure and proper checking would look like this:

// UGLY: we have to proof existence of every
// object before we can be sure property actually exists
if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
	doSomething();
}

7. Passing arguments for function

When function has both required and optional parameters (arguments), eventually we may end up with functions and function calls looking like this:

function doSomething(arg0, arg1, arg2, arg3, arg4) {
...
}

doSomething('', 'foo', 5, [], false);

It’s always easier to pass only one object instead of several arguments:

function doSomething() {
	// Leaves the function if nothing is passed
	if (!arguments[0]) {
		return false;
	}

	var oArgs	= arguments[0]
		arg0	= oArgs.arg0 || "",
		arg1	= oArgs.arg1 || "",
		arg2	= oArgs.arg2 || 0,
		arg3	= oArgs.arg3 || [],
		arg4	= oArgs.arg4 || false;
}

doSomething({
	arg1	: "foo",
	arg2	: 5,
	arg4	: false
});

This is only a rough example of passing an object as an argument. For instance, we could declare an object with name of the variable as keys and default values as properties (and/or data types).

8. Using document.createDocumentFragment()

You may need to dynamically append multiple elements into document. However, appending them directly into document will fire redrawing of whole view every time, which causes perfomance penalty. Instead, you should use document fragments, which are appended only once after completion:

function createList() {
	var aLI	= ["first item", "second item", "third item",
		"fourth item", "fith item"];

	// Creates the fragment
	var oFrag	= document.createDocumentFragment();

	while (aLI.length) {
		var oLI	= document.createElement("li");

		// Removes the first item from array and appends it
		// as a text node to LI element
		oLI.appendChild(document.createTextNode(aLI.shift()));
		oFrag.appendChild(oLI);
	}

	document.getElementById('myUL').appendChild(oFrag);
}

9. Passing a function for replace() method

There are situations when you want to replace specific parts of the string with specific values. The best way of doing this would be passing a separate function for method String.replace().

Following example is a rough implementation of making a more verbose output from a single deal in online poker:

var sFlop	= "Flop: [Ah] [Ks] [7c]";
var aValues	= {"A":"Ace","K":"King",7:"Seven"};
var aSuits	= {"h":"Hearts","s":"Spades",
			"d":"Diamonds","c":"Clubs"};

sFlop	= sFlop.replace(/\[\w+\]/gi, function(match) {
	match	= match.replace(match[2], aSuits[match[2]]);
	match	= match.replace(match[1], aValues[match[1]] +" of ");

	return match;
});

// string sFlop now contains:
// "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"

10. Labeling of loops (iterations)

Sometimes, you may have iterations inside iterations and you may want to exit between looping. This can be done by labeling:

outerloop:
for (var iI=0;iI<5;iI++) {
	if (somethingIsTrue()) {
		// Breaks the outer loop iteration
		break outerloop;
	}

	innerloop:
	for (var iA=0;iA<5;iA++) {
		if (somethingElseIsTrue()) {
			// Breaks the inner loop iteration
			break innerloop;
		}

	}
}

Afterwords

Go ahead and comment! Did you learn anything new? Do you have good tips to share? I'm always delighted for sharing information about all the little details in Javascript.

And if you want to familiarize with Javascript irregularities, I suggest you visiting at wtfjs :).

Webdev Weekly #2 – jQuery 1.4 Edition

January 20th, 2010

There was at least one major event last week related to web development, when the latest version of jQuery was released. This article covers the highlights and most important resources about jQuery 1.4, but in addition includes many other quality resources for web developers.

jQuery 1.4

jQuery 1.4 Released

A general release announcement of jQuery 1.4, provided by the official jQuery 1.4 author, The 14 Days of jQuery.

jQuery 1.4 Fully Released

My quick post about jQuery 1.4 almost right after it was released.

jQuery 1.4 Released: The 15 New Features you Must Know

Good insight in new features of jQuery 1.4, provided by NetTuts+.

jQuery 1.4 Resources For Developers

Collection of resources about jQuery 1.4, provided by W3 Avenue.

jQuery 1.4 Released: Sneak Peek on New Features and Enhancements

And another, useful article about jQuery 1.4, provided by tripwire magazine.

General Web Development

45 Powerful CSS/JavaScript-Techniques

A very useful collection of various CSS and Javascript resources, provided by Smashing Magazine.

33 Beautiful Social Media Icon Sets For Designers And Bloggers

A good collection of icons. Far better than usual, in my opinion.

HTML and CSS

CSS Transitions 101

Nice and comprehensive article about CSS3 Transitions.

Javascript and Scripting Frameworks

jQuery Lint

jQuery Lint is a script written by James Padolsey, which evaluates jQuery code and reports any errors or incorrect usage.

IE CSS3 pseudo selectors

ie-css3.js allows Internet Explorer to identify CSS3 pseudo selectors and render any style rules defined with them. This project is still in progress, but it looks very promising.

Gordon: Flash Runtime Implemented in Javascript

Tobias Schneider has built a Flash runtime that works right in the browser. It’s implemented in pure Javascript and HTML5. Very nice work, indeed!

Author: Samuli Hakoniemi Categories: Web Development Tags: