Web Programming: JQuery Improve Your JQuery – 25 Excellent Tips

Introduction

jQuery is awesome. I’ve been using it for about a year now and although I was impressed to begin with I’m liking it more and more the longer I use it and the more I find out about it’s inner workings.

I’m no jQuery expert. I don’t claim to be, so if there are mistakes in this article then feel free to correct me or make suggestions for improvements.

I’d call myself an “intermediate” jQuery user and I thought some others out there could benefit from all the little tips, tricks and techniques I’ve learned over the past year. The article also ended up being a lot longer than I thought it was going to be so I’ll start with a table of contents so you can skip to the bits you’re interested in.

Table of Contents

1. Load the framework from Google Code

Google have been hosting several JavaScript libraries for a while now on Google Code and there are several advantages to loading it from them instead of from your server. It saves on bandwidth, it’ll load very quickly from Google’s CDN and most importantly it’ll already be cached if the user has visited a site which delivers it from Google Code.

This makes a lot of sense. How many sites out there are serving up identical copies of jQuery that aren’t getting cached? It’s easy to do too…

<script src=”http://www.google.com/jsapi”></script&gt;
<script type=”text/javascript”>

// Load jQuery
google.load(“jquery”, “1.2.6”);

google.setOnLoadCallback(function() {
// Your code goes here.
});

</script>

Or, you can just include a direct reference like this…

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js&#8221; type=”text/javascript”></script>

Full instructions here

2. Use a cheat sheet

Not just a jQuery tip, there are some great cheat sheets out there for most languages. It’s handy having every function on a printable A4 sheet for reference and luckily these guys have produced a couple of nice ones..

http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/
http://colorcharge.com/jquery/

3. Combine all your scripts and minify them

OK, a general JavaScript tip here. But any big project that uses lots of jQuery probably uses lots of plugins (this site uses easing, localScroll, lightbox and preload) so it’s usually applicable.

Browsers can’t load scripts concurrently (well, most can’t, yet), which means that if you’ve got several scripts downloading one at a time then you’re really slowing down the loading of your page. So, assuming the scrips are being loaded on every page then you should consider combining them into one long script before deploying.

Some of the plugins will already be minified, but you should consider packing your scripts and any that aren’t already. It only takes a few seconds. I’m personally a fan of Packer by Dean Edwards

4. Use Firebug’s excellent console logging facilities

If you haven’t already installed Firebug then you really should. Aside from many other useful features such as allowing you to inspect http traffic and find problems with your CSS it has excellent logging commands that allow you to easily debug your scripts.

Here’s a full explanation of all of it’s features

My favourite features are “console.info”, which you can use to just dump messages and variables to the screen without having to use alert boxes and “console.time” which allows you to easily set up a timer to wrap a bunch of code and see how long it takes. They’re all really easy to use too…

console.time(‘create list’);

for (i = 0; i < 1000; i++) {
var myList = $(‘.myList’);
myList.append(‘This is list item ‘ + i);
}

console.timeEnd(‘create list’);

In this instance I’ve deliberately written some very inefficient code! In the next few tips I’ll show you how we can use the timer to show some improvements which can be made.

5. Keep selection operations to a minimum by caching

jQuery selectors are awesome. They make selecting any element on the page incredibly simple, but internally they have to do a fair amount of work and if you go mad with them you might find things starting to get pretty slow.

If you’re selecting the same element time and time again (in a loop for example) then you can just select it once and keep it in memory while you manipulate it to your heart’s content. Take the following example where we add items to an unordered list using a loop.

for (i = 0; i < 1000; i++) {
var myList = $(‘.myList’);
myList.append(‘This is list item ‘ + i);
}

That takes 1066 milliseconds on my PC in Firefox 3 (imagine how long it would IE6!), which is pretty slow in JavaScript terms. Now take a look at the following code where we use the selector just once.

var myList = $(‘.myList’);

for (i = 0; i < 1000; i++) {
myList.append(‘This is list item ‘ + i);
}

That only takes 224 milliseconds, more than 4x faster, just by moving one line of code.

6. Keep DOM manipulation to a minimum

We can make the code from the previous tip even faster by cutting down on the number of times we insert into the DOM. DOM insertion operations like .append() .prepend() .after() and .wrap() are relatively costly and performing lots of them can really slow things down.

All we need to do is use string concatenation to build the list and then use a single function to add them to your unordered list like .html() is much quicker. Take the following example…

var myList = $(‘#myList’);

for (i=0; i<1000; i++){
myList.append(‘This is list item ‘ + i);
}

On my PC that takes 216 milliseconds , just over a 1/5th of a second, but if we build the list items as a string first and use the HTML method to do the insert, like this….

var myList = $(‘.myList’);
var myListItems = ”;

for (i = 0; i < 1000; i++) {
myListItems += ‘<li>This is list item ‘ + i + ‘</li>’;
}

myList.html(myListItems);

That takes 185 milliseconds, not much quicker but that’s another 31 milliseconds off the time.

7. Wrap everything in a single element when doing any kind of DOM insertion

OK, don’t ask me why this one works (I’m sure a more experienced coder will explain).

In our last example we inserted 1000 list items into an unordered list using the .html() method. If we had have wrapped them in the UL tag before doing the insert and inserted the completed UL into another tag (a DIV) then we’re effectively only inserting 1 tag, not 1000, which seems to be much quicker. Like this…

var myList = $(‘.myList’);
var myListItems = ‘<ul>’;

for (i = 0; i < 1000; i++) {
myListItems += ‘<li>This is list item ‘ + i + ‘</li>’;
}

myListItems += ‘</ul>’;
myList.html(myListItems);

he time is now only 19 milliseconds, a massive improvement, 50x faster than our first example.

8. Use IDs instead of classes wherever possible

jQuery makes selecting DOM elements using classes as easy as selecting elements by ID used to be, so it’s tempting to use classes much more liberally than before. It’s still much better to select by ID though because jQuery uses the browser’s native method (getElementByID) to do this and doesn’t have to do any of it’s own DOM traversal, which is much faster. How much faster? Let’s find out.

I’ll use the previous example and adapt it so each LI we create has a unique class added to it. Then I’ll loop through and select each one once.

// Create our list
var myList = $(‘.myList’);
var myListItems = ‘<ul>’;

for (i = 0; i < 1000; i++) {
myListItems += ‘<li>This is a list item</li>’;
}

myListItems += ‘</ul>’;
myList.html(myListItems);

// Select each item once
for (i = 0; i < 1000; i++) {
var selectedItem = $(‘.listItem’ + i);
}

Just as I thought my browser had hung, it finished, in 5066 milliseconds (over 5 seconds). So i modified the code to give each item an ID instead of a class and then selected them using the ID.

// Create our list
var myList = $(‘.myList’);
var myListItems = ‘<ul>’;

for (i = 0; i < 1000; i++) {
myListItems += ‘<li id=”listItem’ + i + ‘”>This is a list item</li>’;
}

myListItems += ‘</ul>’;
myList.html(myListItems);

// Select each item once
for (i = 0; i < 1000; i++) {
var selectedItem = $(‘#listItem’ + i);
}

This time it only took 61 milliseconds. Nearly 100x faster.

9. Give your selectors a context

By default, when you use a selector such as $(‘.myDiv’) the whole of the DOM will be traversed, which depending on the page could be expensive.

The jQuery function takes a second parameter when performing a selection.

jQuery( expression, context )

By providing a context to the selector, you give it an element to start searching within so that it doesn’t have to traverse the whole of the DOM.

To demonstrate this, let’s take the first block of code from the tip above. It creates an unordered list with 1000 items, each with an individual class. It then loops through and selects each item once. You’ll remember that when selecting by class it took just over 5 seconds to select all 1000 of them using this selector.

var selectedItem = $(‘#listItem’ + i);

then added a context so that it was only running the selector inside the unordered list, like this…

var selectedItem = $(‘#listItem’ + i, $(‘.myList’));

It still took 3818 milliseconds because it’s still horribly inefficient, but that’s more than a 25% speed increase by making a small modification to a selector.

10. Use chaining properly

One of the coolest things about jQuery is it’s ability to chain method calls together. So, for example, if you want to switch the class on an element.

$(‘myDiv’).removeClass(‘off’).addClass(‘on’);

source: tvidesign.co.uk

Web Programming: Ajax What is the difference between Body.OnLoad and jQuery document.ready() Event?

The main differences between the two are:

  1. Body.Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery’s document.ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded. Hence, the functions in jQuery’s ready event will get executed once the HTML structure is loaded without waiting for the resources.
  2. We can have multiple document.ready() in a page but Body.Onload() event cannot.

source: codedigest.com

Web Programming: PHP 15 PHP regular expressions for web developers

Regular expressions are a very useful tool for developers. They allow to find, identify or replace text, words or any kind of characters. In this article, I have compiled 15+ extremely useful regular expressions that any web developer should have in his toolkit.

Getting started with regular expressions

For many beginners, regular expressions seems to be hard to learn and use. In fact, they’re far less hard than you may think. Before we dive deep inside regexp with useful and reusable codes, let’s quickly see the basics:

Regular expressions syntax

Regular Expression Will match…
foo The string “foo”
^foo “foo” at the start of a string
foo$ “foo” at the end of a string
^foo$ “foo” when it is alone on a string
[abc] a, b, or c
[a-z] Any lowercase letter
[^A-Z] Any character that is not a uppercase letter
(gif|jpg) Matches either “gif” or “jpeg”
[a-z]+ One or more lowercase letters
[0-9.-] Аny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$ Any word of at least one letter, number or _
([wx])([yz]) wy, wz, xy, or xz
[^A-Za-z0-9] Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4}) Matches three letters or four numbers

PHP regular expression functions

Function Description
preg_match() The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all() The preg_match_all() function matches all occurrences of pattern in string.
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split() The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
preg_ quote() Quote regular expression characters

Validate domain name

Verify if a string is a valid domain name.

$url = "http://komunitasweb.com/";
if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {
    echo "Your url is ok.";
} else {
    echo "Wrong url.";
}


Enlight a word from a text

This very useful regular expression find a specific word in a text, and enlight it. Extremely useful for search results.
$text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor";
$text = preg_replace("/b(regex)b/i", '<span style="background:#5fc9f6">1</span>', $text);
echo $text;


Enlight search results in your WordPress blog

As I just said that the previous code snippet could be very handy on search results, here is a great way to implement it on a WordPress blog. Open your search.php file and find the the_title() function. Replace it with the following: echo $title; Now, just before the modified line, add this code:
<?php
	$title 	= get_the_title();
	$keys= explode(" ",$s);
	$title 	= preg_replace('/('.implode('|', $keys) .')/iu',
		'<strong></strong>',
		$title);
?>

Save the search.php file and open style.css. Append  the following line to it:

strong.search-excerpt { background: yellow; }


Get all images from a HTML document

If you ever widhed to be able to get all images form a webpage, this code is a must have for you. You should easily create an image downloader using the power of cURL.
$images = array();
preg_match_all('/(img|src)=("|')[^"'>]+/i', $data, $media);
unset($data);
$data=preg_replace('/(img|src)("|'|="|=')(.*)/i',"$3",$media[0]);
foreach($data as $url)
{
	$info = pathinfo($url);
	if (isset($info['extension']))
	{
		if (($info['extension'] == 'jpg') ||
		($info['extension'] == 'jpeg') ||
		($info['extension'] == 'gif') ||
		($info['extension'] == 'png'))
		array_push($images, $url);
	}
}


Remove repeated words (case insensitive)

Often repeating words while typing? This handy regexp will be very helpful. $text = preg_replace("/s(w+s)1/i", "$1", $text);  

Remove repeated punctuation

Same as above, but with punctuation. Goodbye repeated commas! $text = preg_replace("/.+/i", ".", $text);

Matching a XML/HTML tag

This simple function takes two arguments: The first is the tag you’d like to match, and the second is the variable containing the XML or HTML. Once again, this can be very powerful used along with cURL
function get_tag( $tag, $xml ) {
  $tag = preg_quote($tag);
  preg_match_all('{<'.$tag.'[^>]*>(.*?)</'.$tag.'>.'}',
                   $xml,
                   $matches,
                   PREG_PATTERN_ORDER);

  return $matches[1];
}

Matching an XHTML/XML tag with a certain attribute value

This function is very similar to the previous one, but it allow you to match a tag having a specific attribute. For example, you could easily match <div id=”header”>.
function get_tag( $attr, $value, $xml, $tag=null ) {
  if( is_null($tag) )
    $tag = '\w+';
  else
    $tag = preg_quote($tag);

  $attr = preg_quote($attr);
  $value = preg_quote($value);

  $tag_regex = "/<(".$tag.")[^>]*$attr\s*=\s*".
                "(['\"])$value\\2[^>]*>(.*?)<\/\\1>/"

  preg_match_all($tag_regex,
                 $xml,
                 $matches,
                 PREG_PATTERN_ORDER);

  return $matches[3];
}

Matching hexadecimal color values

Another interesting tool for web developers! It allows you to match/validate a hexadecimal color value.
$string = "#555555";
if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $string)) {
echo "example 6 successful.";
}

Find page title

This handy code snippet will find and print the text within the <title> and </title> tags of a html page.
$fp = fopen("http://www.catswhocode.com/blog","r");
while (!feof($fp) ){
    $page .= fgets($fp, 4096);
}

$titre = eregi("<title>(.*)</title>",$page,$regs);
echo $regs[1];
fclose($fp);


Parsing Apache logs

Most websites are running on the well-known Apache webserver. If your website does, what about using PHP and some regular expressions to parse Apache logs?
//Logs: Apache web server
//Successful hits to HTML files only.  Useful for counting the number of page views.
'^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+"(?:GET|POST|HEAD) ((?#file)/[^ ?"]+?.html?)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"s+(?#status code)200s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"$'

//Logs: Apache web server
//404 errors only
'^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+"(?:GET|POST|HEAD) ((?#file)[^ ?"]+)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"s+(?#status code)404s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"$'


Replacing double quotes by smart qutotes

If you’re a typographer lover, you’ll probably love this regexp, which allow you to replace normal double quotes by smart quotes. A regular expression of that kind is used by WordPress on contents. preg_replace('B"b([^"x84x93x94rn]+)b"B', '?1?', $text);

Checking password complexity

This regular expression will tests if the input consists of 6 or more letters, digits, underscores and hyphens. The input must contain at least one upper case letter, one lower case letter and one digit.
'A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}z'

WordPress: Using regexp to retrieve images from post

As I know many of you are WordPress users, you’ll probably enjoy that code which allow you to retrieve all images from post content and display it. To use this code on your blog, simply paste the following code on one of your theme files.
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

<?php
$szPostContent = $post->post_content;
$szSearchPattern = '~<img [^>]* />~';

// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );

// Check to see if we have at least 1 image
$iNumberOfPics = count($aPics[0]);

if ( $iNumberOfPics > 0 ) {
     // Now here you would do whatever you need to do with the images
     // For this example the images are just displayed
     for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
          echo $aPics[0][$i];
     };
};

endwhile;
endif;
?>

Generating automatic smileys

Another function used by WordPress, this one allow you to automatically replace a smiley symbol by an image.
$texte='A text with a smiley :-)';
echo str_replace(':-)','<img src="smileys/souriant.png">',$texte);
---
source: catswhocode.com