20. junij 2011

Responsive Web Design: A Visual Guide

Responsive Web Design: A Visual Guide:

These days, “one size fits all” is quickly becoming a dated concept. Luckily, with CSS media queries, we can now easily build responsive web designs that accomodate everything from your mobile phone, up to your massive desktop!


z Matevžem sva spremenila tole


Press the HD button for a clearer picture.
Subscribe to our YouTube and Blip.tv channels to watch more screencasts.

HP EliteBook 8460w, 8560w, and 8760w mobile workstations all go on sale

HP EliteBook 8460w, 8560w, and 8760w mobile workstations all go on sale:


If Dell's latest 17-inch powerhouse is too beastly for your next business trip, HP has begun selling its trio of new EliteBook mobile workstations, with screen sizes as small as 14 inches. In the case of both the 14-inch 8460w and the 15.6-inch 8560w, you get discrete graphics standard and can choose a $1,000 Core i7-2820QM processor, among less pricey options. (With the 15-inch iteration, you can also opt for a 1 billion-color DreamColor display.) Admittedly, you will have to step up to the 17-inch 8760w if you want a Core i7-2920XM CPU, AMD FirePro or NVIDIA Quadro graphics with up to 4GB of memory, and up to three hard drives with RAID 5 support. As promised, they're going for $1,299, $1,239, and $1,899, respectively -- in case your corporate card's just begging for its next hit.

MSI's SteelSeries keyboard-equipped GT780R, GX780 gaming laptops now available

MSI's SteelSeries keyboard-equipped GT780R, GX780 gaming laptops now available: "



MSI managed to turn a few heads back in April by building a gaming laptop around SteelSeries keyboard with its GX780, and it's now announced that both it and the higher-end GT780R model are available with a list price of $1,550 and $1,750, respectively. In addition to that multicolor backlit keyboard, both models pack a 17.3-inch 1920 x 1080 display, a Core i7 2630QM processor, a pair of USB 3.0 ports (plus three USB 2.0), 16GB of RAM, and a 1TB hard drive. So what's the difference between the two? The big one is GeForce GTX 560M graphics with 1.5GB of GDDR5 RAM on the GT780R, compared to a GT555M with 1GB DDR5 of VRAM on the GX780. Head on past the break for the complete press release, and hit up either Amazon or Newegg if you're ready to place an order (both seem to have knocked $100 of MSI's price).

26. maj 2011

Panasonic resurrects Sanyo's pistol-grip camcorders, trots out three new models

Panasonic resurrects Sanyo's pistol-grip camcorders, trots out three new models:


Worried that Panasonic would kill off Sanyo's signature pistol-grip camcorders after it bought its rival last year? Fear not -- Panny just went and resurrected Sanyo's ergonomic design with three new models - slapping its own brand on 'em, of course. And, in a move that would do Sanyo proud, Panasonic brought back the DMX-CA100 / VPC-CA100, a 1080p camcorder Sanyo released last year under the same name. It's gotten a spec boost, though, with the ability to snap 16 megapixel still photos, up from 14.4. The other two -- the HX-DC15 and the HX-DC1 -- both shoot 1080p video as well, with the DC15 offering 16GB internal memory and a 16 megapixel sensor, and the DC1 able to take 14.4 megapixel stills. No word on availability outside Japan, but we're sure those of you with a penchant for flip-out displays and candy-colored plastic will find a way to snag one.

22. maj 2011

The Best of Paul Irish in 2011

The Best of Paul Irish in 2011:

Paul Irish, who works for the Chrome Developer Relations team, is one of the most outspoken and respected front-end developers in our industry. Even better, he has the heart of a teacher, and frequently speaks at conferences, and records screencasts on various web development techniques. Here’s the best of his offerings so far in 2011.



1 – Paul Irish on HTML5 Boilerplate


HTML5 Boilerplate is a “rock-solid default for HTML5 awesome.” In this video, Paul Irish, the man behind the project will show you how you can use HTML5 Boilerplate to get your projects up and running quickly while keeping best practices covered.”



2 – HTML5, CSS3, and Dom Performance



“Paul Irish, from the Chrome Developer Relations team, walks through smart techniques to improve the performance of your app. He describes CSS reflows and how to avoid them, hardware accelerated CSS, animation optimization, web workers, benchmarking and build scripts.”



3 – Chrome Dev Tools Reloaded



“You’re an experienced web developer but new to Chrome Dev Tools’ nuances? Get up to speed on all the newest features of a web app developer’s best friend. Update CSS styles on the fly, get a diff or save changes to disk. Set breakpoints on everything imaginable and dig into the networking stack to uncover performance gains.”



4 – Chrome Developer Tools: 12 Tricks to Develop Quicker



“In this video, Paul Irish, a Chrome developer advocate, presents 12 tips and tricks on how to use Chrome’s developer tools. Learn more…



5 – Quick Color Manipulation

“You can edit the color representation of any CSS color on the fly (from hex to RGB(a) to HSL(a)) and also always view colors in HSL, for example. This lets you manipulate colors easily for finding hover colors or other tweaks live.”




6 – The Build Script of HTML5 Boilerplate: An Introduction



In this video, Paul works his way through the process of using HTML5 Boilerplate’s build script to automatically compress, optimize, and concatenate your files.



7 – 11 More Things I Learned from the jQuery Source

7

As a follow-up to his popular presentation from the jQuery conference, Paul continues with eleven more interesting notes and facts on jQuery.



5. maj 2011

PHP Style Switcher (Free Marketplace File)

PHP Style Switcher (Free Marketplace File):

With a new month comes new free files from all of the Envato marketplaces. For all of May, you can download webfactory’s awesome “PHP Style Switcher” for free from CodeCanyon.


Features

  • absolutely no PHP editing needed!

  • 5 seconds, 3 step setup (see below)

  • created for designers

  • support for multiple CSS files in single HTML

  • ideal for showcasing your work with multiple color schemes

  • faster than JS based switching

  • unlike JS based switching not prone to bugs; doesn’t interfeer with other JS code

  • extensive user-friendly documentation and examples

4. maj 2011

Vim Essential Plugin: NERDTree

Vim Essential Plugin: NERDTree:

In this episode of Vim Essential Plugins, we’ll review the fantastic NERDTree plugin, which is a much improved replacement for the traditional file explorer.



Subscribe to our YouTube and Blip.tv channels to watch more screencasts.



Usage

Begin by downloading the plugin to your Desktop (or any directory, really), and installing it.

cd ~/Desktop
git clone https://github.com/scrooloose/nerdtree.git
cd nerdtree
rake

With those few lines of code, the plugin is now installed! To open a NERDTree panel, in normal mode, we call :NERDTree.

NerdTree

At this point, we can open any file by typing o, or with the more convenient alias, the Enter key. Unlike the default file browser, this will open the new file directly into the buffer to the right of NERDTree, similar to what you might be used to in a program, like TextMate.

If you ever forget what the correct key is for a particular action, press ? to display a quickie help buffer.

Bookmarks

To expedite the process of navigating through your directory structures, NERDTree allows you to conveniently create bookmarks. Do so by moving the cursor to the directory that you wish to bookmark, and then typing:

:bookmark <desired bookmark name>

With this in place, you can now bring up your list of available bookmarks by pressing B. It’s a huge help!


Bookmark Section

Menu

Press the letter m to bring up a menu that will allow you to quickly add, move, copy, and delete nodes (or files). So, for example, if I want to create a new html file within a particular directory, I can type ma newfile.html.


The menu bar

There are plenty more useful shortcuts available, but I’ll leave it to you to discover them. Hint – research the cd and C commands; I use them religiously. Additionally, refer to the screencast above for more shortcuts.


Automated Optimization with HTML5 Boilerplate Build

HTML5 Boilerplate is widely recognized as a rock-solid foundation for building new web-based sites and applications. That said, few are aware that the tool offers more than simply setting up your development environment. It also helps you “wrap up” your work by providing an awesome cross-platform build process.


The Build Script, with Paul Irish




Overview

So why might you need this build tool? Because it’s baked into HTML5 Boilerplate, and can help you automate web performance optimization. We chose to go with Apache Ant to handle the workload. How come?
All other tools have limitations that Ant’s original author couldn’t live with when developing software across multiple platforms.
Many developers are unfamiliar with the build process. But don’t worry; a build tool isn’t a scary monster. Everything can be configured through a relatively simple XML file. This article will help you understand how to set up the build tool, customize the build process and finally change variables and run the build.


The Directory Structure

The build script makes some assumptions about how your files are sorted and structured. Here is the folder structure of HTML5 Boilerplate:

Tutorial image
  • /js/libs/ – contains common script libraries: Modernizr, jQuery and a pngfix for IE6
  • /js/mylibs/ – contains site specific custom library scripts
  • /plugins.js – all jQuery plugins
  • /script.js – site/page specific JavaScript


The Build Folder Structure

The build/ folder contains the following elements:

build.xml

Apache Ant’s build files are written in XML. This file contains our project (Boilerplate Build) and targets. Targets contain task elements. Each task element of the buildfile can have an id attribute and can later be referred to by the value supplied to it, which must be unique.

default.properties

default.properties contains the default build options, project structure and hardcore build options, which we’ll review shortly.

build.properties

This file defines overrides for default.properties. This should be created by a user when he or she needs to override particular values. Consequently, it should not be placed under version control.

tools

Tools are a set of bundles, which include opyipng, JPEGTran, YUI compressor and HTML compressor.



Set up the Build Tool

Because the goal of the build tool is to be platform agnostic, we’ll review the necessary steps to set it up, dependent upon your OS of choice.
  • Windows – Grab and install WinAnt.
  • Mac OSX – Using homebrew, install the following packages: brew install libjpeg optipng. With MacPorts, use the following install command: port install jpeg optipng
  • Ubuntu (Linux) – Using apt, install the following packages: apt-get install libjpeg-progs optipng


Walkthrough of the buildfile

The build tool is nothing more than an XML file that is based on Apache Ant. Below is a walk through of the pre-defined build process. These elements can be configured by editing the build.xml file.

Concatening / Minifying JavaScript


<!-- Optimize javascript files -->
<target name="js.all" depends="js.remove.console, js.all.min, js.main.concat, js.libs.concat, js.concat.scripts,
js.minifyonly.min, js.delete"></target>
<!--  JS: Concat primary scripts -->

...

<!-- JS, Delete concatenated libs file (only if concat.scripts and delete.unoptimized are defined) -->
<target name="js.if.concat.scripts" if="build.delete.unoptimized, build.concat.scripts">
<delete file="./${dir.publish}/${dir.js}/libs-${build.number}.min.js"/>
<delete file="./${dir.publish}/${dir.js}/scripts-${build.number}.min.js"/>
</target>
  • The /js/libs/ files are minified, but not concatenated. Modernizr should be alone in the head of the document. jQuery might be pulled from a CDN, and the pngfix will be included for IE6 only.
  • /js/mylibs/ contains your other various JavaScript libraries and plugins. All files stored here here will be minified (unless they end with .min.js), and then concatenated together.
  • plugins.js and script.js, in the /js/ folder, are all yours. These will also be minified and concatenated with the mylibs/ files.

Minifying CSS


<target name="css" depends="copy">
<echo message="Minifying css..."/>
<concat destfile="./${dir.publish}/${dir.css}/style-${build.number}.css">
<fileset file="./${dir.css}/style.css"/>
</concat>
...
</target>
All CSS files are minified using YUI compressor. The above Ant script will run style.css through YUI compressor for minification.

Image Optimization

<target name="imagespng" depends="copy">
<echo message="Optimizing images"/>
<apply executable="optipng" osfamily="unix">
<arg value="-o7"/>
<fileset dir="./${dir.publish}/">
<include name="**/*.png"/>
</fileset>
</apply>
...
</target>
In HTML5 Boilerplate, we chose to use OptiPng and jpegtran for image optimization for PNG and JPG images, respectively. That said, there are plenty of image optimization tools. Should you wish to do so, you’re free to replace the tools with your own favorite image optimization tools.
For instance, Smush.it uses ImageMagick to identify the image type and convert GIF files to PNG files. It then uses gifsicle to optimize GIF animations by stripping repeating pixels in different frames.

Removing Development-Only Coding

<exclude name="**/${dir.js}/profiling/**"/>
<exclude name="**/${dir.test}/**"/>
...
<target name="js.remove.console" description="Comment out console.log lines">
<echo>Commenting out console.log lines</echo>

<replaceregexp match="(console.log\(.*\))" replace="/\*\1\*/" flags="g" >
<fileset dir="./${dir.publish}/${dir.js}/">
<include name="**/*.js"/>
<exclude name="**/*.min.js"/>
</fileset>
</replaceregexp> 

</target>
Files like console.log, profiling and unit testing files are not needed for the release of the site.

Minifying HTML

<target name="htmlbuildkit" depends="html" >

<apply executable="java" parallel="false" force="true" dest="./${dir.publish}/" >
<fileset dir="./${dir.publish}/" includes="*.html"/>
<arg value="-jar"/>
<arg path="./${dir.build}/tools/htmlcompressor-0.9.3.jar"/>

</apply>
</target>
Listed below are some various options for minifying your HTML files:
  • htmlbuildkit – Preserves comments, multiple spaces and compresses inline JavaScript and CSS.
  • htmlclean – Preserves multiple spaces, removes unneeded quotes and compress inline JavaScript and CSS
  • htmlcompress – Removes unneeded quotes and compresses inline JavaScript and CSS.

Automated Baseline Numbering / Cache Busting

HTML5 Boilerplate uses query string for JavaScript/CSS versioning and cache busting.
HTML5 Boilerplate by default uses query string for JavaScript/CSS versioning and cache busting. The drawback with this approach is that some intermediate proxies – and potentially other clients – may not cache assets that contain query strings. This is due to basic heuristics that flag such requests as dynamic data.

The build tool will first remove the query string versioning and use automated baseline numbering for release control and cache busting.

Configuring Excludes

<exclude name=".gitignore"/>
<exclude name=".project"/>
<exclude name=".settings"/>
<exclude name="README.markdown"/>
<exclude name="**/.git/**"/>
<exclude name="**/.svn/**"/>
<exclude name=".gitignore"/>
<exclude name="*.conf*"/>
<exclude name="mime.types"/>
<exclude name="**/${dir.build}/**"/>
<exclude name="**/${dir.test}/**"/>
<exclude name="**/${dir.demo}/**"/>
<exclude name="**/${dir.js}/profiling/**"/>
Not all files will need to be published. A perfect example of this would be files generated by versioning control system like subversion and git.
By default, there is a list of file types and directories that will be excluded. To add to this list, you can search and find <!-- configurable excludes --> and append your custom exludes to it.


Walkthrough of default.properties

Variables inside the build file are defined in default.properties and build.properties.

Build options

  • build.concat.scripts = true – If set, multiple script files will be smushed together to a single, cohesive file.
  • build.delete.unoptimized = true – If set, unoptimized files will be deleted.
  • file.exclude = nonexistentfile – Excludes file filter for publishing (can’t be empty).

Project Structure

dir.publish = publish
dir.build = build
dir.tools = ${dir.build}/tools
dir.test = test
dir.demo = demo
dir.js  = js
...


The project structure contains directory names, like the ones shown above, as well as the core JS folder, JS utility libraries, and folders which should only be minified but not concatenated.

Other Build Options

  • build.info = buildinfo.properties – Build versioning is defined
  • tool.yuicompressor = yuicompressor-2.4.2.jar – YUI Compressor is defined with yuicompressor-2.4.2.jar


Okay – But How Do I Use This?

Finally, we’ll learn exactly how you can use the build tool in your projects! Refer to the following steps to run the build tool.
  • Open a command line interface, and navigate to your project folder.
  • Navigate into the build folder: cd build/
  • There are four different ways to build your site: the default way is: ant build
  • When the build script changes your HTML to reference the new minified script (usually named something like scripts-002.min.js), it looks for some HTML comments which refer to the beginning and end of the script block. Currently, it looks for <!– scripts concatenated and <!– end concatenated and minified scripts–>.

Build Options

Here’s a list of various build options that you can choose from to suit your particular need:
  • ant build – minor html optimizations (extra quotes removed). inline script/style minified (default)
  • ant buildkit – all html whitespace retained. inline script/style minified
  • ant minify – above optimizations plus full html minification
  • ant text – same as build but without image (png/jpg) optimizing


Conclusion

Performance optimization doesn’t have to be expensive or time consuming. With some reusable rules, one can slowly setup a build process to automate the repetitive aspects of optimization work. Apache Ant provides a powerful, yet easy to use, framework, while HTML5 Boilerplate leverages that to make web optimization as easy as possible for front-end web developers. Thank you so much for reading!

EnOcean's home automation sensors communicate over TCP/IP, play nice with smartphone apps

EnOcean's home automation sensors communicate over TCP/IP, play nice with smartphone apps:

EnOcean has long been on our radar thanks to its inexpensive light switches and thermostats, which harvest energy from solar cells and thermal differentials and boast peel-and-stick backs for easy installation. Now, they're getting hooked up for TCP/IP communication, which means in addition to talking to each other, homeowners will be able to control them using any garden-variety web-connected device. The setup will require a small gateway, at which point you can monitor rooms using desktop widgets and mobile apps such as Can2Go that are compatible with EnOcean's radio protocol (ERP). So far, the company's mostly made headway in retail stores and office buildings, but if it has its way, it could be coming to hospitals, college dorms, and (duh) your home.

Dell's 17-inch Precision M6600 workstation laptop goes on sale early in the UK

Dell's 17-inch Precision M6600 workstation laptop goes on sale early in the UK:

We were promised we'd get Dell's latest Precision powerhouses on May 10th, and that may still be the case for the US, but the company's UK outlet is ready to let you customize and buy an M6600 today. The 17.3-inch laptop offers options for a multitouch display with stylus functionality, a 2.5GHz quad-core Core i7-2920XM CPU, 16GB of DDR3 RAM, up to half a terabyte (2x 256GB) in solid state storage, and NVIDIA Quadro 4000M graphics. Prices start at £1,549 ($2,590) excluding VAT and shipping, though the spec we've listed above would set you back a neat £4,714 ($7,880). Still, a pretty sweet rig if you can afford it.

2. maj 2011

For Your Script Loading Needs

The Problem with Simple Script Tags

They Block the Page

The page stops ‘happening’ while the script is downloaded.

JavaScript files loaded using the script tag are blocking by nature. Everything that’s happening or loading on the page is halted while the script is downloaded and executed. And remember that this applies to each script tag. Some modern browsers may let you download these in parallel, but the rest of the page is still blocked from doing anything meaningful.

No Easy Way to Manage Dependencies

Lack of dependency management is a big drawback.

Next up comes the issue of handling dependencies. For your average web page, you probably don’t need one. Check if your library is loaded and move on. For a non-trivial web application though, this isn’t a great solution. You’ll need to load scripts conditionally based on dependencies. Even then, you’ll still have to figure out the order in which they’re loaded. You can probably do it manually for 3-4 files, but when things begin piling up, you’re probably better off with an automated solution.



Available Choices

The initial idea for this round up was sparked by a post over at Hacker News about making a list of JavaScript script loaders, roughly a month ago. I watched the list balloon up from 3 to a grand total of 10 before I lost interest and moved on.

Now that sufficient time has passed, I think that list is going to be quite massive. Unfortunately, my Google-fu is pretty weak and I can’t seem to find it. If an eagle eyed user manages to find this thread, post in the comments below so I can link to it and hopefully expand my list here as well.

This list is drawn from recommendations by high level web developers who use these tools in their applications.

And as to my choices here, this list represents a superset of recommendations which flowed in after I asked some of the front end community to pitch in with the solutions they’re using. Some of the solutions below may handle dependency managements too, though most stick to simple asynchronous loading. Regardless of the extra niceties, each of the scripts below do one thing with aplomb — load up JavaScripts with minimal fuss.

So without further ado, and in no particular order:



HeadJS

Head JS loads scripts in parallel no matter how many of them and what the browser is. Load scripts like images. Use HTML5 and CSS3 safely. Target CSS for different screens, paths, states and browsers. Make it the only script in your HEAD.

Author: Tero Piirainen

Project URL: Here

Size: 6.3 KB

Related links:



LabJS

LABjs (Loading And Blocking JavaScript) is an all-purpose, on-demand JavaScript loader, capable of loading any JavaScript resource, from any location, into any page, at any time. You can easily specify which scripts have execution order dependencies and LABjs will ensure proper execution order. This makes LABjs safe to use for virtually any JavaScript resource, whether you control/host it or not, and whether it is standalone or part of a larger dependency tree of resources.

Author: Kyle Simpson

Project URL: Here

Size: 4.7 KB

Related links:



RequireJS

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

Author: James Burke

Project URL: Here

Size: 13 KB

Related links:



ControlJS

ControlJS is a JavaScript module that handles both inline scripts and external scripts, delays script execution until after the page has rendered, allows for scripts to be downloaded, not executed and integrates with simple changes to HTML and no code changes

Author: Steve Souders

Project URL: Here

Size: 3.6 KB

Related links:



StealJS

The StealJS project is a collection of command and client based JavaScript utilities that make building, packaging, sharing and consuming JavaScript applications easy. Includes modules for dependency management, JS compression, cleaning and logging.

Author: Brian Moschel

Project URL: Here

Size: 11.4 KB

Related links:



yepnope

yepnope is an asynchronous conditional resource loader that’s super-fast, and allows you to load only the scripts that your users need. It works with both JavaScript and CSS and has a full test suite in QUnit that you can run in your set of supported browsers to make sure it works.

Author: Alex Sexton and Ralph Holzmann

Project URL: Here

Size: 3.4 KB

Related links:



PINF JS Loader

The loader allows for bootstrapping a consistent and state-of-the-art CommonJS environment for any supported platform (on server & in browser) and thus is ideally suited to be used as the target for the commonjs command and the development of cross-platform JavaScript applications and libraries.

Author: Christoph Dorn

Project URL: Here

Size: 22 KB

Related links:



JSLoad

JSLoad is a Javascript file loader that we wrote for Instructables. You give it a set of dependencies and groupings, and it loads the files you need, when your executing code needs them. The real usefulness of JSLoad comes with its ability to group dependencies using tags.

Author: Eric Nguyen

Project URL: Here

Size: 9.8 KB

Related links:



JsDefer

JsDefer features parallel/serial loading based on definitions, dependency, and wrapped versus unwrapped, and whether dependencies are defined in separate def file or in script itself and integration with Deferred (as in jQuery 1.5) enables or simplifies many use-case scenarios among many others.

Author: Boris Moore

Project URL: Here

Size: 4.7 KB

Related links:



JSL (JavaScript Loader)

JSL features on-demand loading, is browser cacheable, dynamic asynchronous JavaScript loading, lazy loading and duplicate source prevention among a ton of other features.

Author: Andres Vidal

Project URL: Here

Size: 2.1 KB

Related links:



YUI 3 Get

The Get Utility provides a mechanism for attaching script and css resources — including cross-domain resources — to the DOM after the page has loaded.

Author: Adam Moore

Project URL: Here

Size: 17.9 KB

Related links:



DominateJS

DominateJS allows you to asynchronously load all your JavaScript, and defer sequential execution until the page loads. DominateJS aims to be a cross-browser and 100% document.write-safe library! This is a heavily modified (and powerful!) evolution of ControlJS.

Author: Chris Joel & Jason Benterou

Project URL: Here

Size: 48 KB



Load.js

load.js is a micro JS lazy-loader. Built on top of chain.js, it allows you to lazy load your JS scripts sequentially or in parallel and handle complex dependency chains.

Author: Chris O’Hara

Project URL: Here

Size: 2 KB

Related links:



BravoJS

BravoJS is an implementation of a proposed draft for CommonJS Modules/2.0

Author: Wes Garland

Project URL: Here

Size: 10.7 KB



Bootstrap

Bootstrap is a small library for dynamically loading JavaScript files.

It’s primary use case is for using in your JS code to load JS files only when they are used.

Author: Scott Koon

Project URL: Here

Size: 1.3 KB



LazyLoad

LazyLoad is a tiny (only 904 bytes minified and gzipped), dependency-free JavaScript utility that makes it super easy to load external JavaScript and CSS files on demand.

Whenever possible, LazyLoad will automatically load resources in parallel while ensuring execution order when you specify an array of URLs to load. In browsers that don’t preserve the execution order of asynchronously-loaded scripts, LazyLoad will safely load the scripts sequentially.

Author: Ryan Grove

Project URL: Here

Size: 1.6 KB



curl.js

curl.js is a small, but very fast AMD-compliant asynchronous loader. Current size: 4.5KB (2.1KB gzipped) using Google’s Closure Compiler.

If you’d like to use curl.js for non-AMD modules (ordinary javascript files), you’ll want to use the version with the js! plugin built in. You may also want to build-in the domReady module. The combined curl+js+domReady loader is still only 6.1KB (2.7KB gzipped).

Author: John Hann

Project URL: Here

Size: 5 KB



$script.js

$script.js is an asynchronous JavaScript loader and dependency manager with an astonishingly impressive lightweight footprint. Like many other script loaders, $script.js allows you to load script resources on-demand from any URL and not block other resources from loading, like CSS and images.

Author: Dustin Diaz

Project URL: Here

Size: 1.4 KB



NBL.js

NBL.js is a tiny script that will make your HTML pages load faster by loading all your JavaScript files asynchronously (in parallel) with the rest of your page. Normally if you include two or three scripts in your page, the browser will wait for them to be executed before your page is shown.

Author: Berklee

Project URL: Here

Size: 971 B

Related links:



That’s a Wrap!

While each of the tools listed above handle script loading in slightly unique ways, be sure to perform your tests when deciding which is the right one for you.

As I mentioned earlier, if you think a loader should be here but isn’t, drop us a line below and we’ll update the roundup accordingly.

Samsung Galaxy S II review

Samsung Galaxy S II review:

If you don't already know all about the Samsung Galaxy S II, where have you been the past two months? The successor to one of the most popular Android handsets to date carries a burden of expectation almost as sizable as its 4.3-inch Super AMOLED Plus screen. It promises to be thinner, lighter, and faster than the Galaxy S that preceded it, while garnishing Android 2.3.3 with a set of TouchWiz customizations that might actually enhance, rather than hinder, the user experience. As such, the Galaxy S II earns Samsung full marks for ambition, but does this slinky new smartphone live up to its interstellar hype? The answer, as always, can be found after the break.

MSI gets a SteelSeries keyboard, builds the GX780 gaming notebook around it

MSI gets a SteelSeries keyboard, builds the GX780 gaming notebook around it:

The worst part about buying a fancy new gaming keyboard? It's hard to show the thing off if it never leaves your basement apartment. MSI's newly announced GX780 notebook combines a colorful backlit 102-key SteelSeries-designed keyboard with the (relative) portability of an 8.6 pound gaming laptop. The keyboard features 1,000 different color combinations, five lighting modes, 10 key simultaneous input, and a layout the company calls 'The Golden Triangle' -- trademark pending, we're sure. The 17.3 inch notebook has some solid non-keyboard specs as well, including GeForce GT555M graphics, a second gen Intel Core i7 processor, and an impressive maximum 16GB of DDR3. No word on pricing or availability, but hopefully the MSRP isn't as colorful as that keyboard. Full press release after the break.

Samsung Galaxy S II begins quest for 120 country domination

Samsung Galaxy S II begins quest for 120 country domination:

How do you best 10 million 14 million in sales of your flagship Galaxy S smartphone? Easy, do what the movie studios do and launch a bigger-budget sequel to an even wider audience. Samsung is holding a media day event in South Korea to celebrate the domestic launch of its smokin' fast Galaxy S II. The dual-core 1.2GHz Gingerbread handset with 4.27-inch 800 x 480 pixel Super AMOLED Plus display, TouchWiz 4.0 UI, MHL port, and 8 megapixel camera capable of 1080p video is already on limited sale in the UK on its way to a 120 country / 140 carrier invasion -- that's plus 10 countries over the initial Galaxy S target. Naturally, we expect variants of the S II, with and without NFC, to hit all the US majors just like the Galaxy S did in its day. Stay tuned to see if our very positive first impressions of this gorgeous 8.49-mm thick superphone carry over to the review which should be up later today.

LG Optimus Big brings a 4.3-inch NOVA display and 1GHz dual-core to the superphone party

LG Optimus Big brings a 4.3-inch NOVA display and 1GHz dual-core to the superphone party:

What's big, mostly white, and set for a Korean launch tomorrow? That's right, the LG Optimus Big! This 4.3-inch whopper, LG's largest handset to date, touts a 1GHz dual-core processor, a slightly skinned Android 2.2 as its OS, HDMI output, a 5 megapixel camera, and 16GB of built-in storage. That spec sheet sounds mighty close to the elder Optimus 2X that launched earlier in the year, though a couple of items have also been borrowed from the still unreleased Optimus Black. They are the NOVA display, which can crank all the way up to 700 nits of brightness, and WiFi Direct, which allows for wireless inter-device communication without the need for an intermediary WiFi access point. This big, delicious spec sandwich is hitting its home market on April 28th, but there's sadly no word on when and where else it might show up. Just keep an eye out for it, shouldn't be that hard to spot.

1. maj 2011

T-Mobile G2x lacks quadband HSPA+, shatters dreams

T-Mobile G2x lacks quadband HSPA+, shatters dreams:



Ever since we first saw it at CTIA, T-Mobile's been advertising its lovely G2x superphone as a quadband HSPA+ capable device. Based on the published specs in press releases and even on T-Mobile's own website, there wasn't any reason to believe that the G2x wasn't compatible with AT&T's 1900 / 850MHz 3G bands, in addition to supporting T-Mobile's 1700MHz "4G" (AWS) flavor and Europe / Asia's 2100MHz standard. This made perfect sense -- especially in light of AT&T's plans to acquire T-Mobile -- until people started purchasing and unlocking the handset. Reports quickly came trickling in that the G2x was unable to connect to AT&T's 3G network, something we verified after unlocking our review unit. That's when we decided that perhaps this was a restriction in the baseband software rather than a hardware limitation, so we reached out to T-Mobile for comment, and received the following statement:

The T-Mobile G2x fact sheet, attached [PDF link], contains accurate information. The T-Mobile website is incorrect and we're working to correct it. The G2x supports 850/900/1800/1900 MHz for 2G/GPRS only, and supports 3G/4G UMTS/HSPA+ bands I and IV. The G2x does not support AT&T's 3G bands. This banding is hardware based.
This is obviously unfortunate news, and is clearly a major faux pas on behalf of T-Mobile. It's particularly disturbing since we were so certain of the G2x's quadband 3G support when we discussed it in our last mobile podcast. Oh well, you live and learn, eh?

Crucial releases m4 SSDs, prices them between $130 and $1,000

Crucial releases m4 SSDs, prices them between $130 and $1,000:

Been yearning for more affordable solid state storage built on an even smaller production process? Crucial's now ready to sate your weirdly specific wants with its 25nm NAND flash-filled m4 SSD, which it has priced at the reasonable level of $130 for a 64GB unit. The company describes it as the fastest drive it has yet introduced, and although early reviews pointed out it'd lost something in read speeds relative to the previous generation, the new m4's improved write speeds and general performance should certainly make that a compelling entry price. More ambitious archivists will be looking to the 128GB and 256GB models, priced at $250 and $500, respectively, while those without a budget will also be given the option to splash $1,000 on a 512GB m4 SSD. All four varieties come in a standard 2.5-inch form factor, support 6Gbps SATA transfers, and are rated to reach read speeds of 415MBps. Availability is immediate and worldwide, so hit the Crucial link below if you're keen on getting one for yourself. Full PR after the break.

T-Mobile G2x review

T-Mobile G2x review:

It's only been a few weeks since the Optimus 2X crossed the desk of our European review bureau as the first known dual-core smartphone in the universe. Now LG's wunderkind has made its way across the pond and landed on US soil to be reborn as the G2x on T-Mobile. While the hardware remains the same elegant Tegra 2-infused slab of glass, metal and plastic, the software has been liberated from the shackles of LG's UI customizations into a serving of vanilla Froyo -- the exact same approach T-Mobile took when it introduced the Desire Z as the G2 without HTC's custom Sense skin last fall. Unlike previous G-series phones, the G2x ditches the physical keyboard for a 4-inch WVGA display with HDMI output and an 8 megapixel camera with 1080p video capture. Beyond the transition from messaging-centric device to multimedia powerhouse, what else is different about the hardware? Is plain Android a vast improvement over the lackluster software that shipped on the Optimus 2X? How does the G2x fare against T-Mobile's current flagship, the Samsung Galaxy S 4G? Find out in our full review after the break.

30. marec 2011

Xtreamer Ultra HTPC grabs a €249 price, May 3rd ship date

Xtreamer Ultra HTPC grabs a €249 price, May 3rd ship date:

We've heard, we've toyed, and we've waited. And now, we're presenting you with two vital nuggets of information surrounding the Xtreamer Ultra HTPC. The Ion 2-based machine is one of the most compact (and most affordable) pre-built HTPCs available, complete with six USB sockets, 4GB of DDR3 memory, an HDMI socket, IR remote and -- if you place a pre-order before the end of April -- a mini wireless keyboard, 8GB USB key, an HDMI 1.4a cable and a fresh copy of Linux. €249 will get one headed your way on May 3rd, or $323 if you're Livin' In America. Hit the source link to get in line, ya heard?

25. marec 2011

ASUS' K53E laptop gets reviewed, 2.53GHz Core i5-2520M CPU gets praised

ASUS' K53E laptop gets reviewed, 2.53GHz Core i5-2520M CPU gets praised:

Never mind the fact that Intel's outing a mid-range laptop CPU long after the highest of high-end -- the 2.53GHz Core i5-2520M is shaping up to be a lovely option for those who'd prefer a budget choice with plenty of horsepower for churning through HD video. The benchmarking gurus over at Hot Hardware recently grabbed hold of the new silicon, and they noticed an 'unmatched performance-per-watt profile for mobile CPUs,' not to mention a robust graphics core, 'ridiculously low idle power consumption,' a respectable price point and plenty of power for any software title not named Crysis 2. ASUS' 15.6-inch K53E was the test machine, and with a starting tag of just $899, it's definitely a compelling package. Based on their testing, this particular CPU was around 15 to 25 percent faster across the board compared to its previous generation 2.5GHz Arrandale counterpart, and that's with around the same power draw, too. Hit the source link for more charts than you'd care to see on an average workday, and be on the lookout for this chip to hit a whole slew of new rigs in the coming weeks.

8. marec 2011

ODROID-A tablet fits 1366 x 768 res on a 10-inch screen, dual-core Exynos inside transparent shell

ODROID-A tablet fits 1366 x 768 res on a 10-inch screen, dual-core Exynos inside transparent shell:

Samsung might not have quite enough Exynos 4210 processors to sell a tablet of its own based on that Cortex-A9 dual-core beastie, but it's found a few to hand over to Korean partner Hardkernel for this here ODROID-A reference platform. It's strictly a dev kit, and as such is unlikely to find its way to your local Best Buy any time soon, but we have to admire the specs on offer. First up is the delightfully dense 1366 x 768 resolution, a rare sight on a 10-inch display, followed by a transparent rear panel that bests anything out on the market right now in terms of sheer sex appeal, and then there are also two MicroSD slots, a HSPA+ modem, HDMI output, a USB 2.0 port, cameras on the front and rear, and a crazy 9000mAh battery. How all this is supposed to only cost $750, we don't know, but then we also don't know how to qualify to get one when it becomes available later this month. So many mysteries. Jump past the break for some hands-on and benchmarking video action.

Plugable DC-125 dock turns your solitary PC into a multiple workstation powerhouse (video)

Plugable DC-125 dock turns your solitary PC into a multiple workstation powerhouse (video):

We've seen a few docking stations 'round these parts that use the venerable DisplayLink technology to great effect, but nothing quite like this before. Plugable's DC-125 USB 2.0 Docking Client connects to your PC allows you to connect your display, speakers, keyboard, and mouse via one USB port -- small potatoes, right? Well, if said PC has a compatible multi-user OS (such as Windows Multipoint Server or Userful Multiseat Linux) you can daisy chain docks to add several terminals to the setup. Terminals! Now you can relive the dark, backwards days when you had to go to the college computer lab to get any work done -- in the comfort of your own home. Available now for $65 a pop. Get a closer look after the break.

Android's everywhere! Xtreamer PVR to serve up a heaping helping of Froyo in your home theater

Android's everywhere! Xtreamer PVR to serve up a heaping helping of Froyo in your home theater:

We got to check out Xtreamer's Prodigy media player and go hands-on with its Ultra HTPC at CeBIT last week, but it turns out that the company has another nifty device set to debut this year. After taking a peek at its 2011 product catalog, we discovered that the Xtreamer PVR is 'comming soon' with a similarly sexy exterior and much of the same specs as the Prodigy, but packing a Sigma Designs SMP8656 chip for high-end 3D graphics, optional dual tuners, and Android 2.2. We sincerely hope that Xtreamer's prowess with Froyo far exceeds its aptitude for spelling -- we kid because we care.

1. marec 2011

NVIDIA Tegra Zone officially launched, takes Android to new dual-core heights

NVIDIA Tegra Zone officially launched, takes Android to new dual-core heights:

It's the first of March, which in NVIDIA land means no longer just talking about Tegra Zone, but actually activating it and letting users see what all the fuss is about. For those who've not yet heard of it, the Tegra Zone is an Android application that curates and highlights content that would most benefit from having the dual-core power of that Tegra 2 chip within your device. At launch, that means a hand-picked selection of games whose makers have gone the extra mile and thrown in additional geometric detail, heavier computation loads, and higher-resolution textures specifically for Tegra 2 smartphones and tablets. The snazzier, more interactive games will still be sourced from the Android Market, the Tegra Zone is no more than a portal unto the vast world of Android content, but it's hoped that its presence will help convey the full value of owning a dual-core mobile device. Even if that value will go down considerably when NVIDIA introduces its quad-core SOC in August -- but, one super chip at a time!

24. februar 2011

HP gets down to business with redesigned and refreshed EliteBook and ProBook laptops (hands-on)

HP gets down to business with redesigned and refreshed EliteBook and ProBook laptops (hands-on):

Two weeks ago 'consumers' got totally redesigned HP Pavilion dv and g-series laptops, leaving those poor guys in the conference room with nothing but their 'old' Calpella-based machines and sad Excel spreadsheets. Well, it's their turn now alright -- HP's been stirring up brand new EliteBook and ProBooks for the guys and gals in suits (though, we're really of the mind that these laptops are for anyone looking for some tough and powerful hardware). All ten of the new machines (yep, 10!) have been given new metal designs, Intel's latest Sandy Bridge processors, facial recognition software, and an easy-access latch to get to the hard drive and RAM. And there's more -- hit the jump for a break down and impressions of each of the models, and don't forget to check those galleries below for some shots of these rigs in the flesh.



Zotac's Fusion-based Zbox AD03 Blu-ray HTPC gets reviewed, smiled upon

Zotac's Fusion-based Zbox AD03 Blu-ray HTPC gets reviewed, smiled upon:

While AMD's Zacate E-350 APU has managed to find its way into a number of laptops, it's not exactly simple to find a desktop based on Fusion right now. Thankfully, Zotac was champing at the bit to be one of the first, and its Zbox AD03 / AD03 Plus has just hit the test bench over at Hot Hardware. All told, the results were fairly predictable, with the Fusion APU running laps around the prior Atom-based version. Of course, 'laps' is a relative term, and while it hasn't single-handedly redefined the SFF PC sector, it has provided a real alternative to Intel's stable of underwhelming nettop chips. Across the board, the Zacate E-350 managed to hold its own, with the only real issue being 'lackluster Flash video acceleration.' We're told that updated drivers are expected to remedy that, however, so there's really little to gripe about from a numbers standpoint. As for value proposition? The AD03 Plus (ringing up at $529.99) seems like a worse deal with its skimpy 2GB of RAM and (comparatively sluggish) 250GB HDD, while the barebones AD03 (which lists for $439.99) could be turned into quite the powerhouse with 4GB of memory and a speedy SSD. Head on down to the source link to get your nerd on, but only if you're interested in scratching that DIY itch that's been so bothersome of late.

20. februar 2011

VMware Android handset virtualization hands-on

VMware Android handset virtualization hands-on:



VMware and LG's virtualized Android OS demo at MWC 2011 is pretty slick. The speed of the transition from the owner's OS to the virtualized OS is nothing short of amazing considering it is all running from the device's SD card. As we posted earlier, the potential in the work world are pretty impressive: an employer can simply provision and add the new OS replete with all the security policies, remote wipe capability, security, VPN config, mail settings, and all that magic. Sure, VMware has started with Android and LG, but there's apparently nothing holding them back from offering this on any smartphone platform -- and honestly, we can't wait to see more. But until then, the following video will have to do.

12. februar 2011

Palm TouchPad leaked: 1.5 pounds, 13mm thick, and just moments from official

Palm TouchPad leaked: 1.5 pounds, 13mm thick, and just moments from official:



According to PreCentral, Palm's forthcoming tablet -- which we suspect will be officially revealed in just a few hours -- will be dubbed TouchPad. They were able to sneak in and hear a few details during the event preparation session, enabling them to confirm that it'll weigh 1.5 pounds and measure 13mm thick (just as we'd heard). If those figures sound familiar, it's because a fledgling startup in Cupertino just so happens to have a slate that aligns exactly to those very specifications. Keep it locked right here for our impending liveblog -- we'll be bringing you the blow by blow as it goes down today in San Francisco.

Update: Robert Scoble seems to have let loose a bit of information as well, confirming that a 10-inch slate is indeed on the docket, as well as 'the smallest little phone' he has ever seen. And before you think that's a positive attribute, he also mentions it being too small to be taken seriously, and definitely not as 'a competitor for the iPhone or Android.' Ouch. Guess we'll have to see for ourselves as the day develops.

Update 2: Oh, boy! The HP Veer, Pre 3 and TouchPad just leaked on HP's official site. We're cautiously optimistic that all these will be on sale later today.

Motorola lifts our spirits with new Atrix 4G video

Motorola lifts our spirits with new Atrix 4G video:

Been feeling down this cold and dreary January? Well, let Motorola 'introduce' you to its new smartphone! The CES conqueror we already know as the Atrix 4G has received its first promo video from the mothership, highlighting its laptop and HD multimedia docks (giving us a decent peek at the docked UI for both), dual-core processor and related gaming credentials, and, of course, that gorgeous qHD screen resolution on the handset itself. It's all set to a very uplifting soundtrack, connoting all the beautiful opportunity and potential that our collective smartphone future holds.

Visualized: Google's periodic table of APIs

Visualized: Google's periodic table of APIs:

The world of Google APIs and developer tools can be a confusing one, but the company has now at least brought a bit of order to the chaos with its own take on the periodic table of the elements. As you can see above, Android occupies the top spot normally reserved for hydrogen in the actual periodic table, and the remaining APIs and developer products are all grouped into their appropriate categories -- and, of course, linked to their respective websites. Hit up the link below to check out the table in its interactive form.

9. februar 2011

Palm TouchPad leaked: 1.5 pounds, 13mm thick, and just moments from official

Palm TouchPad leaked: 1.5 pounds, 13mm thick, and just moments from official:



According to PreCentral, Palm's forthcoming tablet -- which we suspect will be officially revealed in just a few hours -- will be dubbed TouchPad. They were able to sneak in and hear a few details during the event preparation session, enabling them to confirm that it'll weigh 1.5 pounds and measure 13mm thick (just as we'd heard). If those figures sound familiar, it's because a fledgling startup in Cupertino just so happens to have a slate that aligns exactly to those very specifications. Keep it locked right here for our impending liveblog -- we'll be bringing you the blow by blow as it goes down today in San Francisco.



Update: Robert Scoble seems to have let loose a bit of information as well, confirming that a 10-inch slate is indeed on the docket, as well as 'the smallest little phone' he has ever seen. And before you think that's a positive attribute, he also mentions it being too small to be taken seriously, and definitely not as 'a competitor for the iPhone or Android.' Ouch. Guess we'll have to see for ourselves as the day develops.



Update 2: Oh, boy! The HP Veer, Pre 3 and TouchPad just leaked on HP's official site. We're cautiously optimistic that all these will be on sale later today.

8. februar 2011

20 Ways to Save Kittens and Learn PHP

20 Ways to Save Kittens and Learn PHP:

There’s an old adage – dating back to the 1700s – which, in English, says: “A kitten dies each time a PHP programmer doesn’t follow best practices.” Okay, not really; but just go with it!


Getting started in PHP can be a daunting experience. With that in mind, these 20 tips will teach you how to follow best practices, and save lives…kitty lives.





0. Program as Often as You Possibly Can



Programming often and with purpose will make the lessons you learn stick.



Did you study a foreign language in school? Studied all the parts of speech, learned the verbs and how to conjugate them, followed along as your teacher said common phrases?


How much of that language do you still speak?


If you’re answer is, “none,” I’m willing to bet it’s due to the fact that you never actually used the language — you only studied it. But if you can still hold up a conversation, it’s likely because you actually spent some time speaking that language outside of the learning environment. Perhaps you spent a year abroad, or worked a job where a second language was necessary?


Whatever the reason, you retained it because you used it in real-life situations and put it into a personal context that is much easier to recall later.



PHP is a foreign language, just like Spanish or French. In order to become comfortable with it, you need to use it outside of the classroom setting. Tutorials and sample projects are great for teaching the fundamentals, but unless you’re applying those concepts to your own projects, it will be much more difficult to apply those fundamentals in context and burn them into your memory.



So, don’t worry that you “don’t know enough” to build a project. When you choose your project, you have a valid reason to research and implement a concept. Programming often and with purpose will make the lessons you learn stick.




1. Get Familiar with the PHP Manual


Every list of tips for beginners has this tip, and for good reason.


Learning to navigate the PHP documentation is the single most useful thing you can do for yourself as a programmer.



If you look in my browser history at the sites I most often visit, the PHP manual will be right at the top. I don’t suspect that will change for as long as PHP remains my programming language of choice.


At first, the manual does look rather daunting — it doesn’t seem to be particularly easy to browse, and the navigation can be a bit awkward at times. However, you’ll get the hang of it quickly.


Perhaps the best thing to know about the PHP manual is that most functions can be looked up using the pattern http://php.net/function-name in your address bar. For example, to look up the strpos() function, use http://php.net/strpos, and for array_key_exists(), use http://php.net/array-key-exists. (NOTE: pay attention to the omission of parentheses and the substitution of hyphens (-) for the underscore (_) in the address.)


1a. Read the Comments!


It's easy to overlook the comments, but do yourself a favor and have a look through them. If you're getting an unexpected result from a function, chances are someone has spotted it and explained it in the comments.


You can also pick up a plethora of great tips and ideas from the developer community by reading through comments.




2. Take Advantage of the Huge Online PHP Community


In addition to the PHP manual, there are wonderful developer communities all over the internet. Some of my personal favorites include StackOverflow.com and the W3Schools.com forum.


Additionally, Twitter is a surprisingly excellent place to post PHP questions. If you tag a tweet with #PHP, it's likely someone in the community will spot it and lend a hand.


A Note About Twitter: Of course, anything that's useful will inevitably be overrun with spammers and those sorry individuals who deeply misunderstood the purpose of social media. If you're going to use Twitter as a support network, you'll probably want to routinely block or hide the accounts which spew job postings or retweet everything that mentions PHP.



Just remember: as you get better, please try to pay it forward. The development community needs everyone to pitch in, and it won't be long before you'll have the ability to answer questions for other beginners. Don't turn a deaf ear.





3. Don't Put Off Best Practices for Later


As you're learning, you're going to hear a lot about 'best practices' in programming; stuff like prepared statements and PEAR coding standards.


Do not put off learning this stuff because it seems hard.



If something is a best practice, it's not because we (meaning other PHP developers) got together and said, 'How can we make life harder for the noobs?'



Best practices exist to keep your scripts secure, fast, and manageable. Learn them as early as you can. In fact, don't even bother learning the wrong way.


It takes just about the exact same amount of learning to figure out mysql_query() as it does to learn PDO or MySQLi. So if you start with your choice of the latter two, you're starting with a strong foundation in database interaction and, really, you've put in less overall effort.


Be sure to browse Nettuts+ for a variety of tutorials on PHP best practices, including prepared statement usage.




4. Don't Put Off Best Practices for Later!


I just wanted to make sure you saw this.



Seriously, folks. Don't take shortcuts. Every time you violate best practices because the right way seems 'too hard,' BP dips a kitten in crude oil.



So if you won't do it for yourself, your projects, your peers, or the advancement of the community at large, at least consider the kittens.




5. Make Code Self-Documenting



If you need to squeeze characters off your variable names to shave .2ms off your script’s execution time, there’s likely a whole different problem going on.



It's tempting, early on, to be 'clever' with your variable and function names. Maybe you read an article about performance, or saw a code snippet that accomplished a ton of work in two lines of code. Maybe you want to create your own 'signature style' of coding. Maybe you just heard that I hate it and you wanted to piss me off.


Whatever your temptation, resist it at all costs.


Consider the following snippet of code:


<?php

$a = b('jason.lengstorf@copterlabs.com');

$c = explode('@', $a);

$d = $c[1];

echo 'The email address ', $a, ' belongs to the domain ', $d, '.';

function b($e) { return htmlentities($e, ENT_QUOTES); }

?>

Does that make any sense to you?


Of course, you can figure out what it does, but why force anyone trying to work in your code to spend the extra 1-5 minutes scratching his head, trying to remember what $c is storing.


So let's take that code and make it self-documenting:


<?php

$email = sanitize_string('jason.lengstorf@copterlabs.com');

$email_pieces = explode('@', $email);

$domain = $email_pieces[1];

echo 'The email address ', $email, ' belongs to the domain ', $domain, '.';

function sanitize_string($string) { return htmlentities($string, ENT_QUOTES); }

?>

There. Much better. Now, just by glancing at the code, you can get the general idea of what's going on. No head-scratching, no muttered curses, and most importantly, no real difference.


Sure, you save a few bytes with short variable names. But, honestly, if you need to squeeze characters off your variable names to shave .2ms off your script's execution time, there's likely a whole different problem going on.




6. Add a Comment to Anything You Had to Think About



Comments are the sign of a competent programmer.



Comments are not the sign of a novice. In fact, as I see more and more code that's not mine, I'm starting to think that comments are the sign of a competent programmer, as they seem to be the only ones doing it.


If your code is self-documenting, you won't require too many comments. However, no matter how clear your variable and function names are, you'll always have spots where the action taken simply isn't that obvious.


When that happens, slap a comment in there. 'Future You' will give 'Present You' a high five when the time comes to update the script.



As a rule of thumb, if you had to stop and think for a few seconds about what needed to happen to make the script work properly, it's probably a good spot for a quick note.



Consider the following:



$pieces = explode('.', $image_name);
$extension = array_pop($pieces);

What does that do? Did you have to stop and think about it? Do you still not know for sure what's stored in $extension?


Look at that snippet again, but with one quick comment:



// Get the extension off the image filename
$pieces = explode('.', $image_name); $extension = array_pop($pieces);

Now, even if you don't know how or why that code works, you at least know that $extension refers specifically to an image extension. If that saves 'Future You' or another developer five seconds of processing the script's intent, it was well worth your ten seconds of effort to add the comment in the first place.


As with most things, moderation is key. Too few comments and you risk leaving the next developer (or Future You) puzzled by a code snippet, which can even lead to accidental breaking of code because the solution, without explanation, might look silly or superfluous. Too many and it becomes too difficult to scan through your code, which is equally frustrating.


Moderation is key.




7. Learn Docblock and Use It


If I could be sure every developer in the world would do one thing with absolute consistency, I think it would be the use of the Docblock commenting standard.


I have a few reasons for my strong support of Docblock:



  1. It requires one to think about the what and why for each file, function, method, and so on.

  2. It gives a clear description of the expected types for parameters and return values in functions/methods

  3. It provides a quick description of what the code does

  4. When coupled with one of the many IDEs that support Docblock, it creates code hinting (which allows you to see a description and expected parameters/return values for the method or function you're using)


This tip does border on the upper level of beginner, but I group this under 'best practices to be learned as quickly as possible.' Feel free to skip it, but before you do, think about the kittens.


Docblock shows its versatility best when used to document a class:



/**
* A simple class to get the sum or difference of $_foo and a value
*
* @author Jason Lengstorf <jason.lengstorf@copterlabs.com>
* @copyright 2011 Copter Labs
* @license http://www.opensource.org/licenses/mit-license.html
*/

class CopterLabs_Test
{

/**
* The value to use in addition and subtraction
* @var int
*/
private $_foo = 0;

/**
* Adds a value to $_foo and returns the sum *
* @param int $add_me The value to add to $_foo
* @return int The sum of $_foo and $add_me
*/
public function add_to_foo( $add_me=0 )
{
return $this->_foo += $add_me;
}

/**
* Subtracts a value from $_foo and returns the difference
* @param int $subtract_me The value to subtract from $_foo
* @return int The difference of $_foo and $subtract_me
*/
public function subtract_from_foo( $subtract_me=0 )
{
return $this->_foo -= $subtract_me;
}

}

At first it might look overwhelming, but the benefits are very much worth taking the time to familiarize yourself with the syntax.


The above Docblock, when used in Netbeans, will generate the following code hint:


Code hinting in Netbeans



8. Don't Be Too Hardcore to Use an IDE


If you don't already know the type, you will soon: the developers who think real programmers don't use IDEs.


Now, look: if you want to impress people, learn to juggle. Refusing to use anything but Emacs in the command line to write scripts will not get you chicks or grant you instant hacker status; it will, however, hang a sign on your forehead warning your coworkers that you are, in fact, That Guy.


Don't be That Guy.



There is nothing wrong with using software to give you on-the-fly syntax highlighting, error-checking, and code hints.



How in-depth your IDE goes is entirely up to you. Personally, I really like Netbeans. I've heard tons of praise for Coda for Mac (though it's not really an IDE), and I previously used Eclipse before moving to Netbeans.


Whatever IDE you choose, you'll see your coding speed increase and your facepalm-worthy bugs decrease. Further, as you expand your code library, you'll have code hinting for all of your custom software. (Because you're using Docblock, right? Right?!)


Don't think IDEs are uncool -- no matter what 'That Guy' tries to tell you.




9. Group Common Code Into Functions



If you see an action repeated, it's time to strongly consider moving that code into a function.



When you first start programming, it's easy to start at the top of the page and work down, adding each piece of code right where it's needed.


However, when you code this way, you'll begin to notice that certain pieces of code are appearing over and over again. This is a minefield when it comes to maintenance and upgrades, because you have to hunt through each file for every occurrence of that action to change its functionality.


If you see an action repeated, even if it's only twice, it's time to strongly consider moving that code into a function.


Consider the following for example:


$unclean1 = '<a href="javascript:alert(\'Holy Crap!\');">Click Me!</a>';

$detagged1 = strip_tags($unclean1);
$deslashed1 = stripslashes($detagged1);
$clean1 = htmlentities($deslashed1, ENT_QUOTES, 'UTF-8');

$unclean2 = "Let's call Björn!";

$detagged2 = strip_tags($unclean2);
$deslashed2 = stripslashes($detagged2);
$clean2 = htmlentities($deslashed2, ENT_QUOTES, 'UTF-8');

echo $clean1, "<br />", $clean2;

As you can see, both of those strings required a few steps before they could be considered safe to use. However, you'll also notice that those same steps could be considered necessary for every bit of information that is passed to the script.


This is an instance where using a function instead is far more desirable:



$unclean1 = '<a href="javascript:alert(\'Holy Crap!\');">Click Me!</a>'; $unclean2 = "Let's call Björn!";

$clean1 = sanitize_input($unclean1);
$clean2 = sanitize_input($unclean2);

echo $clean1, "<br />", $clean2;

function sanitize_input( $input )
{
$detagged = strip_tags($input);
$deslashed = stripslashes($detagged);
return htmlentities($deslashed, ENT_QUOTES, 'UTF-8');
}

By wrapping the common code in a function, it's a bit easier to see what's going on, and it's much easier to edit the steps you want to take when sanitizing your input.




10. Group Related Functions Into Classes


Getting a handle on OOP is another one of those things that I file under 'best practices to learn as quickly as possible.'



If you have a handful of functions that all deal with database actions, you can save yourself a lot of time and effort by grouping them into classes.



Learning object-oriented programming is definitely outside the scope of this list, but I felt it was definitely worth mentioning in this beginners' list.




11. Use Constants, Not Globals



PHP allows you to define your own constants with the function define().



When I first started programming on larger projects, I found myself using global variables more often than seemed necessary or reasonable. Admitting you have a problem is the first step.


I was storing things like application-wide data (such as the site's name or the maximum image width) and database credentials in variables, and I found myself required to use the $GLOBALS superglobal to access this information.


Then I realized PHP allows you to define your own constants with the function define().


A constant is a great way to store information like the aforementioned app-wide data and database info. An additional bonus is that it can't be modified, so you can't accidentally overwrite your database password somewhere later in the script.


As a matter of best practices, the use of globals is generally discouraged to begin with, so the use of constants is preferred anyways. Review the following code for an example and see for yourself:


<?php

define('FOO', 'constant value');

$bar = 'global value';

echo baz();

function baz()
{
$constant = ' Constant: ' . FOO;
$global = 'Global: ' . $GLOBALS['bar'];

return $constant . "<br />\n" . $global;
}

?>



12. Don't Be Afraid to Use Includes


Often, as you're building larger products, it will make a lot of sense to break it apart into smaller chunks, or include files.


A generally accepted way to look at includes is to put any bit of code that will be used in multiple scripts into an include file (such as your database connection details, the header and footer data that is common across the whole site, utility functions like your input sanitization actions, etc.) so it can be pulled in by the file that needs it, rather than being copy-pasted.


For example, on a site with multiple pages, a standard template may emerge that looks something like this:


<?php

// Application-wide data and database connection
require_once 'constants.inc.php';
require_once 'database.inc.php';

// Utility functions
require_once 'utilities.inc.php';

// Header markup
require_once 'header.inc.php';

/* * Page-specific processing goes here */

// Footer markup
require_once 'footer.inc.php';

?>



13. Don't Obsess Over Performance


This is a point of near-paralysis for some developers, and it's really too bad; there is a blurry line between writing efficient code and wasting time trying to squeeze an extra 5ms out of a script's execution.


Definitely read a few performance articles and learn some of the major pitfalls that can drag your scripts to a slow crawl, but don't waste extra time refactoring your code to change double quotes to single quotes because you found out it was a tiny fraction faster.



Use your head, avoid the big problems, and keep your ears open, in case a tip you've never heard comes along to speed up your code, but don't make it a race.



No one can tell the difference between a 25ms page load and a 40ms page load. Make sure it's not 700ms and move on to more important things.




14. Avoid Marrying HTML to Your Scripts


This can be tricky, but do your best to avoid tangling up your HTML markup in your PHP. It's nearly impossible to get away from it completely, but try to make sure that you don't include any non-essential HTML markup in your code.


Consider the following:



echo '<div class="example-div"><p>This is some test content.</p></div>';

Was it necessary for that code to wrap the paragraph tag in a div? Could it have been modified to only include the paragraph tag that holds the text? Have a look at an alternative solution:



<div class="example-div">
<?php echo '<p>This is some test content.</p>'; ?>
</div>

Note: This example is grossly oversimplified. Generating HTML with PHP is usually more of an issue when dealing with a complex function or method that organizes a dataset. The point I'm trying to make is that it can sometimes be tempting to include more markup than is necessary in the output.


In most cases you can keep the HTML outside the PHP, which makes things easier to read and, usually, easier to work with as well.




15. Try to Use at Least One Unfamiliar Concept in Every Project



Push yourself outside your comfort zone.



You're never going to learn if you keep doing the same old thing. Try out a concept that you're not quite comfortable with on every project you possibly can.


Don't be over-ambitious, but definitely push yourself outside your comfort zone. It gives you a challenge, saves you from getting bored doing the same old thing over and over again, and forces you to progress as a developer.


Look at the project, find all the bits that you know well (or at least well enough), and then pick an area you'd like to understand. Sign up for it. Then do it.




16. Don't Be Too Proud to Change


You will be wrong. Frequently. But that's not a bad thing.


As you improve, you'll find newer, better solutions to problems that you've faced in the past. Don't feel stupid; you're learning.


But it's extremely important that you don't become attached to the code you write. Don't think your way is better just because it's your way. If you happen across a great solution that makes yours look like a Band-Aid on a bullet wound, use it! Pay attention to what's different and what you did that could have been better. File that away under, 'Things I've Learned.'



Never allow yourself to believe that an inelegant solution is acceptable because it's yours. That's hubris (which, if you're not aware, doesn't generally result in happy fun times).





17. Validate


If you're a web programmer, start becoming familiar with input validation as soon as possible.


Keep in mind: validation is quite different from sanitization.



Input validation is the practice of making sure data matches the format you've requested, like checking an email field for a valid email address or ensuring that a submitted username is 8-20 alphanumeric characters.



It can be tedious and a pain in the ass, but making sure that only valid data makes it through your processing scripts will enhance the user experience and avoid a lot of bugs in the scripts that have to use the data later on.




18. Whitelists Instead of Blacklists



If you're not on top of your blacklist, vulnerabilities appear.



In plenty of situations, you'll want to block or get rid of certain tags, words, email addresses, or other various bits of data.


A common solution is to use a blacklist: a collection of the tags, terms, etc. that aren't allowed.


This poses a problem, however; you have to be more clever than the person trying to do something naughty. For instance, in the case of disabling JavaScript in posts, you might blacklist the onclick attribute, as well as most of the event attributes, but what if you forget one? What if a new one is added to the spec sometime in the future?


If you're not on top of your blacklist, vulnerabilities appear.


However, to save headache later, use a whitelist whenever possible. A whitelist is the opposite of a blacklist: a collection of allowed tags, terms, etc.


For instance, in the strip_tags() function, you can provide a whitelist to specify which tags are allowed in strings:



strip_tags($string, '<em><strong><tt>');

Now your problem is most likely going to be that you can actually do less than you wanted, but that's far safer and usually less of an emergency to handle.


You can't get away with it in every situation, but saying what is allowed vs. what isn't will provide you with more confidence and control over your scripts.




19. Learn to Count Like a Computer


Are you looking for tip #20? Remember that in nearly all cases, counts in PHP start at 0, so this is actually the 20th tip. You'll find this to be the case in most languages; don't let this one trip you up!




Summary


If you're a beginner, the tips covered above will help you take great strides toward good habits and best practices. Don't get overwhelmed if all of this is news to you; take things one step at a time (see tip #15).


Want to talk specifics? Discuss this post on the forums.



"