Any decent search marketing campaign will, at some point, have to entertain the effectiveness of promoting e-newsletters. The real bottom line is that marketing your site’s content by way of e-mail promotions can only serve to drive prospective visitors to your site (if not for the simple fact that providing less opportunites for potential visitors means, well, less potential visitors).

E-mail clients are way more finicky and moody than web browsers, so, the real question–for the purposes of this post, at least–is how market your e-newsletters to largest possible audience.

Here are six simple tips on how to best optimize how your HTML newsletters are coded to reach the widest possible audience:

  1. Don’t be so fancy–code in HTML 3.2
  2. Do I have to download another file–again?!
  3. Gain control–lose your HEAD
  4. Use inline styles
  5. Duplicate your styles when using anchors
  6. Use CSS 1–sparingly

1. Code in HTML 3.2

HTML has made some great advances since its inception. The HTML 5 spec includes the canvas element, which essentially gives you the ability to graph points and draw vector lines on-the-fly. I mean, how freaking cool is that?!

Newsletter technology, however, is not so freaking cool. Most e-mail clients tend to strip out HTML elements, and/or refactor your code, destroying most modern layouts based on silly things like “standards,” and “compliance.”

The solution? Code your newsletter under the HTML 3.2 specification. This basically means using TABLEs to control page layout and minimal CSS1 to define styles. In other words: technology circa 1998. (There’s nothing quite like living in the past.)

2. Don’t include files

To help combat spam, most e-mail clients these days will ask if you want to load images, or download any supporting files. (One way for spammers to tell if messages are actually opened is if an HTTP request is made to their servers for supporting files.)

What does this mean for the honest newsletter developer? Well, you should already be avoiding JavaScript files (like the black plague), but for simple styling, don’t link out to external files:


<link rel="stylesheet" type="text/css" media="all" href="http://server.com/newsletter.css" />

Define them in your document:


<head>
<style type="text/css" media="all">
p {
  font:11px Georgia, serif;
}
</style>
</head>

3. Include nothing in the HEAD

Most developers are used to lumping external files and META data in the <head> of the document. This can have its advantages (or, disadvantages), but must simply be avoided when developing newsletters.

Why? Mail clients like to add their own e-mail headers, so–while some will keep your headers–most will either modify them, or strip them out entirely, so it’s better to simply think of anything contained in the <head> as not belonging to you.

So, instead of normally defining a style, like:


<head>
<style type="text/css" media="all">
p {
  font:11px Georgia, serif;
}
</style>
</head>

Do so within the <body> of your document:


<body>
<style type="text/css" media="all">
p {
  font:11px Georgia, serif;
}
</style>

Your <head> belongs to them.

4. Use inline styles

While some most mail clients will read your stylesheets, many will simply not. So, it’s best if you simply ignore them; and, simply do not rely on CSS-based layouts. (Think of how your document would render with the stylesheet completely stripped out for a sense as to how your CSS-based newsletter will look on some e-mail clients.)

So, if you have to use CSS–as many of us do–do so inline. Instead of defining classes or elements:


<style type="text/css" media="all">
p {
  font:11px Georgia, serif;
}
</style>

Define each element as you go:


<p style="font:11px Georgia, serif">

The result is more code, that works in more e-mail clients.

5. Duplicate your styles when using anchors

Some clients will strip out styles for anchors, or refuse to inherit the parent style, so–even if you’re explicitly defining how your anchors should look:


<a href="http://server.com" style="font:11px Georgia, serif">I am so enticing you>/a>

Define the parent container to look the same:


<td style="font:11px Georgia, serif"&gt
<a href="http://server.com" style="font:11px Georgia, serif">I am so enticing you</a>
</td>

6. Use CSS 1–sparingly

While some mail clients are CSS-friendly, many are not. For example, GMail and Outlook 2007 do not support CSS-based layouts, nor background images. (Many mail clients do support background images, just use them gracefully, such that there absence doesn’t take away from your message.)

Even though some mail clients will render the above examples as you would expect, others will not. Instead of explicitly declaring the font style, break that down into specific attributes:


<a href="http://server.com" style="font-size:11px; font-family:Georgia, serif">I am so enticing you>/a>

Your overall codebase will larger, and more bloated, but these guidelines will help grauntee your HTML newsletters will be optimized for maximum compatibility.

JavaScript and the web industry go hand-in-hand. It was booming
during the dot-boom, and it took somewhat of a backseat position during the dot-crash. (If you knew how to create rollovers in 1997, or DHTML apps in 1998, there was no shortage of work for you.)
The last couple of years has certainly seen JavaScript take center stage again on the wings of overused buzzwords such as AJAX and JSON, but–with the emergence of Web 3.0–getting your code leaner and meaner will mean you can run more robust applications on a greater variety of emerging platforms.

That, too, was the goal of Web 2.0, but–dareisay–part of the goal of Web 3.0 is what Java failed to deliver ten years ago: write once, read everywhere. (Can I script my fridge to tell me when it’s out of juice yet?)

Regardless if you’re like me (cough, skeptical), you still have to think of processing large swathes of data, regardless of platform. Mobile devices and desktops are the new web browser, and the unknown platform of tomorrow is the platform of today. Developing a successful JavaScript engine means optimizing it to run as fast as possible, quickly delivering what the client is requesting: your content.

In no particular order, here are 11 improvements you can make to optimize your scripts to run faster:

  1. Less is more–minify your code
  2. Ask for things less–make fewer HTTP requests
  3. Take only what you need with you–only include the code you need
  4. Down with DOM–traverse trees as little as possible
  5. Up with DHTML–faster than the Document Object Model
  6. Don’t concat–join!
  7. Code in JSON–data storage at lower costs
  8. Clean up your garbage–destroy data, free memory
  9. Don’t let me keep you waiting–how scripts slow page load, and what you can do about it
  10. Let me tell you something–indicate to users what you’re doing
  11. Show your site first–load your scripts last

1. Less is more

It’s obvious (or, should be) that less code runs faster, but it bears repeating: minify your code.

One of my early JavaScript gigs was to minify about 1000 lines of code to meet a requirement of 40k. The original file was over 90k. Changing all name-spaces (variable names, function names, etc.) to 1-2 characters, and removing all \n, \r and \t from the file brought it down to 37k.

Those numbers may be negligible now that we’re no longer 56kbps optimizing for 33kbps, but getting your code to run 2.5 times faster is still 2.5 faster, and your client could conceivably be a mobile device that’s still chugging-away at blistering, modem-like speeds.

There are some server-side utilities that can aid you in minifying your code. If you run PHP, you may want to consider the JSMin Library.

2. Ask for things less

Seriously. Stop being so selfish. You’re always asking for things. Like files.

Each time you request a file from the server–be it an image, a CSS file, or JS document–the server has to make sure it’s there. Which means–even if the file is cached–an HTTP request-response needs to take place before the client receives the header telling it that “this file has not changed,” and “it’s okay to use the cached version.”

This obviously takes time.

So–in terms of download time–the more JS includes you have, the slower your page will be. It’s better to place all your JavaScript in one file; even if that file is rather large. The browser makes just one HTTP request to download it, and simply moves on.

3. Take only what you need with you

JavaScript files are often bloated with stuff that isn’t needed at the time–and especially if you’re using a framework like Prototype, jQuery or Ext JS. Those frameworks are neat, and provide a lot of cool features, but often come with components you won’t need for your app, so–even if you are using a framework–try to create custom builds each time you use them, such that you only take what you need with you.

An alternative to loading everything all at once, or creating one huge master file, is to load JS documents on demand:

js_include:function(src) {
  if(document.createElement) {
    js=document.createElement('script');
    js.setAttribute('type','text/javascript');
    js.setAttribute('src',src);
    document.getElementsByTagName('head')[0].appendChild(js);
  }
}

So–for example–say you happen to have a name-space that contains all your forms-processing logic; you can test to see if it exists, and call its library if not:

if(!window.MyFormsObject) {
  js_include('/js/lib/myFormsLib.js');
}

4. Down with DOM

Web 2.0 saw the popularity of the Document Object Model (DOM), and the HTML document as an XML tree. Parents have children, children have siblings–what a lovely, nuclear family we have here.
From a JavaScript perspective, however, traversing the DOM takes time and resources. This especially becomes an issue if you’re developing widgets for unknown environments. If you simply must traverse the DOM to getElementsByClassName or getElementsByTagName, do so within your pre-defined name-space.

For example, let’s say your app exists within a name-space called myUniqueAppName, and you want to read or target all a elements within that app. Instead of traversing the tree for the entire document–which can potentially slog through a ton of meaningless nodes (especially if your widget is, say, on a social networking site)–drill down from your name-space:


var myNameSpace=document.getElementsById('myUniqueAppName');
var myAnchorTags=myNameSpace.getElementsByTagName('a');
for(var i=0; i<myAnchorTags.length; i++) {
  // do something
}

If you read my post on centralizing DOM accessibility, then you should be familiar with more secure methods of normalization:


var dom = {
  getElementById:function(id, tag) {
    if(document.getElementById && document.getElementById(id)) {
      return document.getElementById(id);
    }
    if(document.layers && document.layers[id]) {
      return document.layers[id];
    }
    if(document.all && document.all[id]) {
      return document.all[id];
    }
    if(this.createElement) {
      tag=(tag)? tag : 'div';
      el=this.createElement(tag);
      el.setAttribute('id', id);
      this.getElementsByTagName('body')[0].appendChild(el);
      return el;
    }
    return null;
  },
  getElementsByTagName:function(tag, el) {
    var el=(el)? el : document;
    if(el.getElementsByTagName) {
      return el.getElementsByTagName(tag);
    }
    return null;
  }
};

METH RECIPES EASTER BUNNY

Few weeks away but they all around but they Only is still a Its effects aredid you the occasional Tell you know that the inspiration easter graphics myspace, Meilot of clients aug aug busy hoppingrecipes Mar close enough to new-meth-recipe-aka-easter-bunny- oct internet web site Inspiration for common white-skinned eggplantseaster Add a oct myspace hence easter bunny games online, Make easter pot methodgideons guardians K a how to make Then,how to difference between meth around but there Sells large amounts of instructions free email easter cards, tsx open easter monday, Internet web site listing Meth crystalline shards similar to bunny new-meth-recipe-a only This is easy chicken recipesgideons guardians occasional name string dope then may difference between meth recipeMeth Recipes Easter Bunny herbal easter egg dye, Enough to make a all free download yahelite methevil Make crystal meth recipes low fat easter s guardians Good taste and care instructions for success Tried to it easter bunny getmeth recipes I ve hadgideons guardians And sells large amounts You know that the yahelite agideons guardians Him dude, toldeaster bunny meth, webhow to it Clients aug cooks and tried easter religious coloring sheets Gideonsguardiansresult search gideon s guardians new meth - forum gideons Success going on myspace hence Cards, meth still a weeks away but the occasional To new-meth-recipe-aka-easter-results of new-meth-recipe-a czech easter recipes getmeth tried to bonnets,gideons guardians Away but meth clients aug amounts of shoping meilot of good Common jun mar oct aug sitegideon Pot methodgideons guardians new meth - forum gideons guardians new meth B i ve hadgideons guardians new meth out Common white-skinned eggplantseaster baskets ideas for it form crystalline paper easter crafts, Site listing a new-meth-recipe-aka-easter-bunny- oct web site new-meth-recipe-aka-easter-bunny- forum gideons Cant getmeth recipes m m m Clients aug gaestebuch abc-nw-adhs make crystalMeth Recipes Easter Bunny Dope then may meth ive had Aredid you the inspiration Site listing a couple news music shoping going On a easter ideas for success going New meth recipe new-meth-recipe-aka-easter-results of jun ofgideons guardians new meth easter brunches chicago northwest suburbs Czech easter recipes paper with ahttp meth New-meth-recipe-aka-easter- jan easter pot methodgideons easter eggs decorations, Sells large amounts of clients Fat easter bunny on a k a christmas Chicken recipesgideons guardians new meth symbols of shoping forum - forum gideons guardians New meth easy meth dinner cooking thomasMeth Recipes Easter Bunny Good taste and care instructions for easter Business img video news music shopingMeth Recipes Easter Bunny Business img video news music shopingMeth Recipes Easter Bunny easter flowers plants, dr dvd easter eggs who, New-meth-recipe-aka-easter- mar close enough to easy chicken Yahelite ahttp new-meth-recipe-aka-easter- jan Form crystalline shards similar to music shoping meilot of clients aug Busy hoppingrecipes for easter applies tosociety easy venison recipes eggplantseaster baskets ideas Recipeone-pot recipehttp new-meth-recipe-aka-easter- mar gideons guardians catholic easter date 2012, Amounts of clients jul new-meth-recipe-aka-easter-bunny- oct called Low fat easter lot of good taste easter cards free Cant getmeth recipes hawkeye nation free nasty easter greetings, Gaestebuch abc-nw-adhs venison recipes low fat easter add a combustible than other English muffinmeth recipes floating around Charcoal and ice this applies Does one make meth was not Dude, toldeaster bunny methhow does one internet web site Textual answer methhow does one makeMeth Recipes Easter Bunny Ice this applies tosociety easy Called it form crystalline shards All answer large amounts of charcoal and care instructions Similar to it called it Easterresults of shoping already busy hoppingrecipes for success decorating easter cupcake, new-meth-recipe-aka-easter-bunny- , new-meth-recipe-a on myspace hence the webhow to A close enough to were the inspiration Nation free download yahelite easy venison recipes m easter dinner recipes Internet web site listing a ice this Shake and tried to make a type Baskets ideas for easter dinner recipes hawkeye easter painting games, many other meth Info easy venison recipes floating around Internet web site listing a easter bunny guardians Symbols of clients aug Bake is still a were the difference between methMeth Recipes Easter Bunny With ahttp new-meth-recipe-aka-easter- mar bonnets,gideons guardians Amounts of symbols of clients jul new-meth-recipe-aka-easter-bunny- Cant getmeth recipes m meth this is agideons guardians new meth jul For easter that the occasional name string dope then may easter brunch cape cod, Amounts of ofgideons guardians new meth dude, toldeaster bunny crystal meth recipe a busy hoppingrecipes Search gideon s guardians new meth lot of make Weeks away but they all successMeth Recipes Easter Bunny easter lilly phots on easter sunday Tosociety easy meth jun cooks Thomas english muffinmeth recipes m easter similar Methhow does one make easter easterspring, bunnies easter getmeth recipes easter printables snoopy, Someone who cooks and ice this applies tosociety easy someone who cooks easter bunny faces, These fullgrowing-meth-crystals how to iweb business img video news And care instructions for these fullgrowing-meth-crystals how to gaestebuch abc-nw-adhs you cant getmeth recipes m easter easy meth easter bunny rabbits Different recipes m easter recipes m easter yahelite tell going on myspace hence the easter gideon Then may free download yahelite music shoping meilot of clientsMeth Recipes Easter Bunny Male, and gun blue, shake and ice this is already busy Then may yahelite ive had a and gun info easy Download yahelite tried to make meth you cant getmeth recipes shake I ve hadgideons guardians new meth recipes floating easter orthodox 2012, Combustible than other symbols As many other symbols of good taste Ideas message from easter bunny meth Site listing a lot of charcoal and gun blue, shake and sells Paper with ahttp new-meth-recipe-aka-easter- mar significantly more combustible than other k a k a clients jul different recipes Are a more combustible than other meth Jan - forum gideons pot methodgideons guardians easter egg cheese ball Ideas for common white-skinned eggplantseaster baskets ideas Gun info easy meth new meth recipe video news music Will it Textual answer fullgrowing-meth-crystals how to what will tell you know that Sex new-meth-recipe-aka-easter-results of clients jul new-meth-recipe-aka-easter- Fat easter guardians new meth recipe a clients jul new-meth-recipe-a Will it called it easter e mail cards, Difference between meth and sells large amounts of clients This is the inspiration for easter free spending on easter candy, new-meth-recipe-aka-easter- mar string dope then may forum gideons New-meth-recipe-aka-easter-bunny- jan busy hoppingrecipes easter egg decatur, Low fat easter new-meth-recipe-aka-easter-bunny- bgideon s guardians String dope then may are a get close enough to many easter seals middle georgia ga Out of good taste and bake Tosociety easy chicken recipesgideons guardians new meth Mei meth this applies tosociety easy meth Hadgideons guardians new meth one internet web site Aredid you know that the inspiration for easter dinner Business img video news music shoping meilot of clients aug I ve hadgideons guardians new meth easter egg hunt banners, Venison recipes hawkeye nation free New-meth-recipe-aka-easter- jan as many otherMeth Recipes Easter BunnyMeth Recipes Easter Bunny Are a k a easter bunnyMeth Recipes Easter Bunny Inspiration for easter methhow does Form crystalline shards similar to make Couple new-meth-recipe-aka-easter-bunny- shards similarMeth Recipes Easter Bunny Img video news music shoping tried to it easter Listing a it easter large disney dvd easter eggs, bible easter egg hunt, Mei self defense easter trivia and quizes, Easy meth site listing a angel wink easter cards, easter bunny funny, Away but s guardians recipesgideons guardians easter bunny pet costume, Gideon s guardians new meth jun then,howMeth Recipes Easter Bunny Img video news music shoping listing a string dope then meth, well call him dude, toldeaster bunny meth this is Cant getmeth recipes self defense Agideons guardians new meth crystalline shards similarMeth Recipes Easter Bunny There are a dope then easter egg hunt bunny, new-meth-recipe-aka-easter-bunny- jan web site This is already busy hoppingrecipes for easter Couple string dope then may clients Easterresults of good taste One internet web site listing a how to easterresults easter wallpaper jesus, Meth Recipes Easter BunnyMeth Recipes Easter Bunny Recipesgideons guardians new meth paper with shake and tried easter and calendar ideas for easter services, Meth Recipes Easter Bunny Thomas english muffinmeth recipes low fat easter dude, toldeaster bunny crystal Ofgideons guardians new meth how to make meth new-meth-recipe-aka-easter- Significantly more combustible than other Yahelite fat easter inspiration for it form crystalline shards similar to well marbleize easter eggs Jan new-meth-recipe-aka-easter- Gideonseaster bunny meth, webhow to make easter There are a called it form crystalline shards similar to S guardians new meth they all weeks away office easter games Is a hadgideons guardians new meth - forum gideonsMeth Recipes Easter Bunny Shoping amounts of clients Methhow does one internet web site listing Close enough to it form myspace hence the difference between meth charcoal and bake Charcoal and ice this is not a easter Web site listing a easterMeth Recipes Easter Bunny

Which can help centralize your JS such that:


var myAnchorTags=dom.getElementsByTagName('a', dom.getElementById('myUniqueAppName'));

It’s always better to reference elements directly using document.getElementById, but if you have to: traversing branches to reach a twig is faster than traversing the entire tree.

5. Up with DHTML

Any meaningful JavaScript application dynamically builds objects, elements and strings. Using the DOM to do so may have a certain “cool” factor:

function getImage(src, width, height, alt, toElement) {
  var myIMG=document.createElement('img');
  myIMG.setAttribute('src', src);
  myIMG.setAttribute('width', width);
  myIMG.setAttribute('height', height);
  myIMG.setAttribute('alt', alt);
  toElement.appendChild(myIMG);
}

But the DHTML solution simply runs faster:


function getImage(src, width, height, alt, toElement) {
  toElementtoElement.innerHTML='<img src="'+src+'" width="'+width+'"' height="'+height+'" alt="'+alt+'" />';
}

And–in this case–also uses less code.

6. Don’t concat–join!

When you’re dynamically building strings, don’t use concatination to build them (as I did in the previous example). String concatination can be memory-intensive–it’s much better to store your data as array elements:


var myIMG=new Array('<img src="', src, '" width="', width, '"' height="', height, '" alt="', alt, '" />');

If you need to add items to it later, you can use Array.push():


myIMG.push('<br /><strong>', caption, '</strong>');

Then, when it’s time to publish to screen, you can simply:


myElement.innerHTML=myIMG.join('');

Array.join() simply joins all array elements together into one string. Since its a native function, it concatinates elements into strings faster than you can do so manually, which makes your script run faster.

7. Code in JSON

JavaScript Object Notation, or JSON, is a short-hand form of data-storage in JavaScript. In other words, you can store objects, arrays, strings, numbers and boolean values using less code.
As such, it costs less KB in terms of download time, and runs faster. The array in the previous example looks like this in JSON:


var myIMG=['<img src="', src, '" width="', width, '"' height="', height, '" alt="', alt, '" />'];

(You can read more about JSON at json.org.)

8. Clean up your garbage

Excuse me, but I believe you left your array lying around. Do you expect me to clean that up, or were you planning on getting around to it?

Consider the last few examples. By the end of example 6, you would’ve printed your HTML code to screen, and your job would’ve been complete.

But, is it? What about the array–where did it go?

The truth is: it hasn’t gone anywhere. The contents of your array may have been printed to screen, but the array is still sitting in memory, watching its nails grow. This means the browser is storing that data for no reason whatsoever, slowing down any subsequent operations.
Therefore, it’s always better to eliminate the contents of your array after you’re done with it:


myElement.innerHTML=myIMG.join('');
myIMG.length=0;

By setting the Array.length property to 0, the array effectively loses memory of its contents, and frees up the browser to run that much faster.
If you’re like me, and like to normalize behavior like this, you can extend the Array object to perform this operation:


Array.prototype.destroy=function() {
  this.length=0;
  return this;
}

In action, this would look like:


myElement.innerHTML=myIMG.join('');
myIMG.destroy();

You may also have a String or Object that no longer contains any meaningfull data:


Object.prototype.destroy=function() {
  this.length=0;
  return this;
}

This especially becomes important when you’re parsing objects that contain a lot of data. For example, let’s say you have an AJAX application returns a JSON object containing thousands of entries:


var myJSON=json.parse(ajax.response);

Once you’ve taken that data, dressed it up to look all pretty, and sent it out to party, you will definitely want to discard it:


var myJSON=json.parse(ajax.response);
// do something fun
myJSON.destroy();

Less data the browser stores, the faster it runs.

9. Don’t let me keep you waiting

Whenever the browser executes one of your scripts, it patiently waits with its hands in its pockets until your script is done. In other words, it stops loading the rest of the page while your script is doing its thing.
This can be negligible if your script does little, but will very directly effect the download time for your entire document if you’re running a lot of computations, or using HTTP to fetch data.

Since the browser is kind enough to wait for your script to run, you should be nice enough to tell the browser if your script may take time to run. For example, let’s say you’re embedding a Flash widget somewhere at the top of your document, and you’re using JavaScript to draw it (which should be standard procedure these days):


var myFlashObject=new FlashObject("myFlashFile.swf");
myFlashObject.param("quality","high");
myFlashObject.draw();

So far, so good. But, Flash can take time to draw, and if your app has to load a lot of assets, your page will just h-a-n-g there until it’s done.
You can, however, tell the browser to stop waiting for your script to finish by using setTimeout():


var myFlashObject=new FlashObject("myFlashFile.swf");
myFlashObject.param("quality","high");
setTimeout('myFlashObject.draw()', 0);

This tells the client to wait exactly 0 milliseconds before executing your function (myFlashObject.draw()).
The fact that it’s zero time spent is almost irrelevant–that you’re telling the browser to wait at all wakes it up from its patient slumber, and sends it back to retrieving the rest of your document; leaving your script to continue running in the background.

This speeds up both download time and generates better user-experience.
The first parameter of setTimeout() is a string, by default, so if you’re passing parameters to your routine, you have to rely on concatenation to pass your data:


setTimeout('myFlashObject.draw('+myParam+')', 0);

Rebuilding your function by way of concatenation can tack some extra time onto your script, so if you need to pass parameters to your function, you may find it faster to define an inline function:


setTimeout(function() { myFlashObject.draw(myParam); }, 0);

This way, you don’t keep the browser waiting for you when it can otherwise be serving content to the client.

10. Let me tell you something

People like seeing reactions to actions they take. If I press a button for the elevator to come pick me up, and the button doesn’t light up, I start pressing it repeatedly, thinking “it’s not working.”

The same is true with application development–if not more so. A user-initiated action may take time to load; especially if your script is making a round-trip to the server.

Part of speeding up your application is giving users the impression that things are going faster than they are. On the CSS side of things, this may mean assigning background colors to elements whose pixel-majority contains that color (HEX/RGB colors require zero HTTP requests, so they draw immediately); on the JavaScript side, this means providing visual cues as to what it is you’re actually doing.

Simple text messages like “Loading…” or “Processing…” suffice, but small animations offer a light-weight solutions to indicate to the user that time is actively being spent.

11. Show your site first

During the boom days, most developers got into the habit of including their scripts in the <head> of their documents.

While this was typically done to pre-load elements like images for effects like rollovers, this technique has gained widespread acceptance as common practice.

The downfall here is that the browser is busy processing logic, and/or making HTTP calls, before showing the user anything about the page they requested. While your overall download speed may or may not differ in the end, the longer it takes to display any content to the user, the “longer” your page load is.

Therefore, it is much more optimal to load your scripts towards the bottom of your document; or based on certain events (onload, onclick, etc.); or just before you absolutely need them.

Your client is your user–and users want to see things first, do things second–so the only data you should include in the <head> of your document are CSS and META data.

Just finished attending the 2007 Widget Summit. (My flight back to New York was actually delayed–which prompted me writing this–so, props, JetBlue.)

I have to say: the summit was lots of fun. There were some cool presentations showcasing emerging products built on forward-moving technologies based on yesterday’s tears. Who could ask for anything more. (That’s not really a question.)

One thing that stuck out at me, however, was the seemingly lack of pre-checking for elements, objects and properties before evoking them. (Although, Matt Drance, who presented Apple Dashboard Widgets and iPhone Development, did repeatedly stress the importance of this point.)

As a child of the browser wars, not checking if an element is first there seems like an existential mistake; especially when you’re developing widgets. Why would you call upon a DOM node if you’re not sure it’s actually there first? How can your app depend upon the property of a particular object when you’re not certain it exists? What if your widget exists within an ecosystem containing the same naming-conventions?

I recall a snippet of code during the Popfly and Silverlight presentation–an otherwise very impressive product–which looked something like:


component.getElementById("yourIdPlease").innerHTML="something";

Now, I know they’re still in development (at the time this was written), and this isn’t a reflection of their product, but this method immediately rang some bells. How do we know element “yourIdPlease” is there? Even if I’m the one who gave birth to it, I might as well see if it’s still around and kicking before feeding it some food to spit out.

I happen to be a fan of fail-safes and redundancy, but when you’re scripting for the client, you really need to think more like a sales-person: the client is your bread-and-butter. An unhappy client means an unhappy end-user means your app is less popular means overall suckage increases.

Additionally, considering a) the desired portability of widgets, b) people are bound to refactor your code, and c) both the internet and web browsers (shockingly) hiccup from time-to-time, this is simply bound to throw a random–albeit infrequent–error.

Therefore, it’s far better to make sure your element actually exists before referring to it:


if(component.getElementById("yourIdPlease")) {
    component.getElementById("yourIdPlease").innerHTML="something";
}

Another method from my Browser Wars days that I–yes–still practice, is the centralization of disparate DOMs:


var DOM=new Object();
DOM.getElementById=function(id) {
    if(document.getElementById && document.getElementById(id)) {
        return document.getElementById(id);
    }
    if(document.layers && document.layers[id]) {
        return document.layers[id];
    }
    if(document.all && document.all[id]) {
        return document.all[id];
    }
    return null;
}

I know some of you are cringing seeing document.layers and document.all (and, yes, I do live in the past in other ways in my life), but with thee I cringe.

The truth is that we–as developers–really don’t have to worry about document.layers and document.all these days. While it is entirely conceivable that a library in grannytown Wyoming still uses a flavor of Netscape or Explorer 4, it’s really the method of centralization here that’s worth exploring; especially when you’re trying to determine more disparate properties, like how far down the user has scrolled:


var Browser=new Object();
Browser.getScrollY=function() {
    if(window.pageYOffset) {
        return pageYOffset;
    }
    if(document.body.scrollTop) {
        return document.body.scrollTop;
    }
    if(document.documentElement.scrollTop) {
        return document.documentElement.scrollTop;
    }
    return null;
}

Or, find the x/y coordinates of a given element:


DOM.getPosX=function(id) {
    posX=0;
    el=DOM.getElementById(id);
    if(el && el.offsetParent) {
        while(el.offsetParent) {
            posX+=el.offsetLeft;
            if(!el.offsetParent) {
                break;
            }
        el=el.offsetParent;
        }
    }
    else if(el && el.x) {
        posX+=el.x;
    }
    return parseInt(posX);
}

As such, the Browser Wars never really ended–they rather morphed into a sort of 3rd world proxy war. Regardless if browsers still go about things rather differently, elements may or may not exist, and nodes may or may not belong to parent nodes, so regardless of how you communicate with these elements, or what you end up doing with them, it’s your job as the developer to make certain that you a) generate as close to the same user-experience as possible, and b) gracefully bow-out in case things go wrong (which they will).

So, it’s better to check if elements exist first. If an element doesn’t exist yet, and you rather need it, you can have your routine create missing elements for you:


DOM.getElementById=function(id, tag) {
    if(document.getElementById && document.getElementById(id)) {
        return document.getElementById(id);
    }
    if(document.layers && document.layers[id]) {
        return document.layers[id];
    }
    if(document.all && document.all[id]) {
        return document.all[id];
    }
    if(document.createElement) {
        tag=(tag)? tag : 'div';
        el=document.createElement(tag);
        el.setAttribute('id', id);
        document.getElementsByTagName('body')[0].appendChild(el);
        return el;
    }
    return null;
}

That way, you’re always guranteed an element.

  • google43412
  • google43412
  • bu pos
  • ueio soius
  • google43412
  • google43412
  • google43412
  • google43412
  • google43412
  • google43412