Toolkit for web developers.

noviembre 17, 2010 Deja un comentario

When develop a website or web app, it is not easy make a great experience for each browser or device that uses it.  It is important to have in mind some general topics like response time, availability and consistency

As Gomez define in their Best of the Web Report (2009):

Response time measures the end-to-end time elapsed while downloading each Web page or the entire multistep transaction process. This includes the base HTML page and any referenced objects, third-party content, JavaScript and Cascading Style Sheets and other Web content. The reported metric represents the average time required to download the homepage or execute the multistep transaction without factoring in user latency.

Availability measures the percentage of successfully completed tests out of total test attempts for the period. Availability rates are dependent upon a number of variables including the ability of our testing agent to access the Website, its ability to process a transaction without error, and its ability to download each step of the transaction within a reasonable 60-second time frame. Reported availability rates do not include errors related to the Gomez measurement system or scripting problems.

Consistency measures the standard deviation of the response times of successful tests. The goal is to have a low number (in seconds), which indicates how consistent the response time is each time a user visits a Website. Highly variable response times (in seconds) indicate inconsistent performance that may be caused by poor Website performance as measured across diverse geographies, issues with Internet peering or an under-powered technical architecture which leads to slowdowns during periods of peak traffic.

In this post I show some tools that help us to improve our work as developers, it covers tools for debug, analyze, document, minify, monitor and test the apps.

Browser Tools

The browser tools are plug-ins or tools that are directly embedded in the browsers, the list with the original description as it appears on the website of each tool.

Firebug

http://getfirebug.com/

Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.

  • Inspect and edit HTML
  • Tweak CSS to perfection
  • Visualize CSS metrics
  • Monitor network activity
  • Debug and profile JavaScript
  • Quickly find errors
  • Explore the DOM
  • Execute JavaScript on the fly
  • Console logging for JavaScript

Firebug Lite

http://getfirebug.com/firebuglite

Compatible with all major browsers: IE6+, Firefox, Opera, Safari and Chrome, You can extend it and add features to make it even more powerful.

YSlow

http://developer.yahoo.com/yslow/

YSlow analyzes web pages and suggests ways to improve their performance based on a set of rules for high performance web pages (http://developer.yahoo.com/performance/rules.html).  YSlow is a Firefox add-on integrated with the Firebug web development tool. YSlow grades web page based on one of three predefined rule set or a user-defined rule set. It offers suggestions for improving the page’s performance, summarizes the page’s components, displays statistics about the page, and provides tools for performance analysis, including Smush.it™ and JSLint.

Smush.it

http://www.smushit.com/ysmush.it/

Image optimization is an art few have mastered. Useful image editing tools exist that allow images to be edited to reduce their file size while retaining image quality. Using these tools is a good start for optimizing images, but more can be done using advanced tools like Smush.it.

Smush.it uses optimization techniques specific to image format to remove unnecessary bytes from image files. It is a “lossless” tool, which means it optimizes the images without changing their look or visual quality. After Smush.it runs on a web page it reports how many bytes would be saved by optimizing the page’s images and provides a downloadable zip file with the minimized image files.

Smush.it is included with YSlow and is no longer available as a separate download. Download YSlow now to get Smush.it and start saving bytes on image files.

Page speed

http://code.google.com/speed/page-speed/

Page Speed is an open-source project started at Google to help developers optimize their web pages by applying web performance best practices. Page Speed started as an open-source Firefox/Firebug add-on and is now deployed in third-party products such as Webpagetest.org, Show Slow and Google Webmaster Tools.

Page Speed is a family of tools for optimizing the performance of web pages.

  • The Page Speed Firefox/Firebug add-on allows you to evaluate the performance of your web pages and to get suggestions on how to improve them.
  • The mod_pagespeed Apache module automatically rewrites pages and resources to improve their performance.

Web Inspector

The Web Inspector from safari, gives you quick and easy access to the richest set of development tools ever included in a browser. From viewing the structure of a page to debugging JavaScript to optimizing performance, the Web Inspector presents its tools in a clean window designed to make developing web applications more efficient. To activate it, choose Show Web Inspector from the Develop menu.

  • Choosing Safari Menu Option
  • Choosing Preferences…
  • Choosing the Advanced Tab
  • Enabling “Show Develop menu in menu bar“

Speed tracer

http://code.google.com/webtoolkit/speedtracer/

Speed Tracer is a tool to help you identify and fix performance problems in your web applications. It visualizes metrics that are taken from low level instrumentation points inside of the browser and analyzes them as your application runs. Speed Tracer is available as a Chrome extension and works on all platforms where extensions are currently supported (Windows and Linux).

Using Speed Tracer you are able to get a better picture of where time is being spent in your application. This includes problems caused by JavaScript parsing and execution, layout, CSS style recalculation and selector matching, DOM event handling, network resource loading, timer fires, XMLHttpRequest callbacks, painting, and more.

Chromium Benchmarking Extension

http://www.chromium.org/chrome-benchmarking-extension

The Chromium Benchmarking Extension is a quick-and-dirty way to test page load time performance within Chrome.

  • Can clear the cache between each page load
  • Can clear existing connections between each page load
  • Works with both SPDY and HTTP
  • Measures time-to-first-paint, overall page load time KB read/written, and several other metrics
  • Can compare performance between SPDY (http://www.chromium.org/spdy)  and HTTP

Internet Explorer Developer Toolbar

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=95e06cbe-4940-4218-b75d-b8856fced535

The Internet Explorer Developer Toolbar provides several features for exploring and understanding Web pages, is not compatible with Internet Explorer 8. These features enable you to:

  • Explore and modify the document object model (DOM) of a Web page.
  • Locate and select specific elements on a Web page through a variety of techniques.
  • Selectively disable Internet Explorer settings.
  • View HTML object class names, ID’s, and details such as link paths, tab index values, and access keys.
  • Outline tables, table cells, images, or selected tags.
  • Validate HTML, CSS, WAI, and RSS web feed links.
  • Display image dimensions, file sizes, path information, and alternate (ALT) text.
  • Immediately resize the browser window to a new resolution.
  • Selectively clear the browser cache and saved cookies. Choose from all objects or those associated with a given domain.
  • Display a fully featured design ruler to help accurately align and measure objects on your pages.
  • Find the style rules used to set specific style values on an element.
  • View the formatted and syntax colored source of HTML and CSS.

IE Developer Tools

http://msdn.microsoft.com/en-gb/library/dd565628%28VS.85%29.aspx

Every installation of Internet Explorer 8 comes with the Developer Tools. This tool enables Web site developers to quickly debug Microsoft JScript, investigate a behavior specific to Internet Explorer, or iterates rapidly to prototype a new design or tries solutions to a problem on-the-fly.

Getting started with the tools is simple: press F12 or click Developer Tools from the Tools menu.

Opera Dragonfly

http://www.opera.com/dragonfly/

Opera Dragonfly allows you to develop more quickly and easily by providing tools to debug your JavaScript and to inspect the DOM, CSS, network traffic and data stores. Developing for mobile has never been easier with Opera Dragonfly’s built-in remote debugging. Opera Dragonfly can be activated from the Developer Tools menu or by right-clicking and selecting Inspect Element. Opera Dragonfly’s source is available to view,  it is released on a Apache 2.0 license.

  • Debug JavaScript
  • Inspect the DOM
  • Redefine your style
  • Monitor the Network
  • Dig through your storage
  • Spot your errors
  • Design Utilities
  • The Opera debug menu
  • Debug your phone or TV

Opera Dragonfly allows you to debug web pages from your desktop, that are being displayed on your mobile phone remotely (with opera mobile), to see how go to this article http://my.opera.com/ODIN/blog/opera-mobile-10-and-its-remote-debugging-party-trick.

Standalone tools

These tools go beyond of the browser tools and give you insights more professionals about what is happening in your web apps.

Dynatrace AJAX Edition

http://ajax.dynatrace.com/ajax/en/Default.aspx

dynaTrace AJAX Edition is the most powerful tool for optimizing your Web 2.0 applications. With so much code executing in the browser, it’s getting more and more difficult to keep your apps light and responsive. AJAX Edition v2.0 is a community-driven release that goes beyond debugging and diagnostics.

  • Analyzes your code and tells you were your hotspots are
  • Recommends proven solutions to common Web 2.0 problems
  • Compares your site’s performance to your competitors’
  • Provides deep insight across AJAX, Javascript, rendering, caching, & more
  • Supports Internet Explorer 6, 7, and 8

Showslow

http://www.showslow.com/

Show Slow is an open source tool that helps monitor various website performance metrics over time. It captures the results of YSlow, Page Speed and dynaTrace AJAX Edition rankings and graphs them, to help you understand how various changes to your site affect its performance.

HTTP Watch

http://www.httpwatch.com/

HttpWatch is an integrated HTTP sniffer for IE and Firefox that provides new insights into how your website loads and performs, has a comprehensive  automation interface that can be used by most programming languages (e.g. C#, Javascript & Ruby). The interface can be used to control the HttpWatch plug-in for IE or Firefox and to access data in HttpWatch log files.

  • HttpWatch captures a wide range of HTTP related data including:
    • Headers and Cookies
    • URLs and method (e.g. GET, POST, etc)
    • Parameters sent in a query strings and POST requests
    • HTTP status codes and errors
    • Redirections
    • The network size of the HTTP response including headers
    • Chunked encoding
  • Integrates With Internet Explorer and Mozilla Firefox
  • Compact & Comprehensive Log Files
  • Includes a Standalone Log File Viewer
  • Summary of Recorded Traffic
    • Performance
    • Page Events
    • Timings
    • Status Codes
    • Errors
    • Warnings
  • Grouping Of Requests By Page
  • Real-Time Page Level Time Charts
  • Request Level Time Charts
  • Page Level Events
    • DOM Load
    • Page Load
    • Render Start
    • HTTP Load
  • Detects Potential Problems

Fiddler

http://www.fiddler2.com/fiddler2/

Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic between your computer and the Internet. Fiddler allows you to inspect all HTTP(S) traffic, set breakpoints, and “fiddle” with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language. Fiddler is freeware and can debug traffic from virtually any application, including Internet Explorer, Mozilla Firefox, Opera, and thousands more.

Monitoring iPhone web traffic (with Fiddler)
You can ‘sniff’ the web traffic coming from an iPhone, to see how go to this link: http://conceptdev.blogspot.com/2009/01/monitoring-iphone-web-traffic-with.html

Mite

http://mite.keynote.com/

Mite is a powerful, desktop-based tool for testing and validating mobile Web content. Mite will reduce your time to market and help you deliver a better end-user experience. With a customizable library of over 1,800 devices and 11,000 device profiles, Mite gives you unequalled access to screen compatibility and application support information.

Keynote Mite lives on your desktop giving you instantaneous feedback. Navigate a site and validate that content appears as you’ve intended while checking that links are functioning properly. Mite also provides a download summary, a performance summary, re-directs, headers, cookies and detailed waterfall graph for further investigation.

Charles Debugger

http://www.charlesproxy.com/

Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).

Charles makes debugging quick, reliable and advanced; saving you time and frustration

  • Records all traffic between your browser and the Internet
  • Reveals the contents of all requests, responses, cookies and headers
  • Supports SSL and HTTPS
  • Saves valuable time
  • Simulates slower internet connections
  • Download statistics
  • Configurable
  • Quickly find and eliminate bugs

With Charles Debugger You can debug iphone web apps, to know how, see: http://blog.mediarain.com/2009/08/iphone-http-connection-debugging/

JSDoc toolkit

http://code.google.com/p/jsdoc-toolkit

JsDoc Toolkit is an application, written in JavaScript, for automatically generating template-formatted, multi-page HTML (or XML, JSON, or any other text-based) documentation from commented JavaScript source code.

YUIDoc

http://yuilibrary.com/projects/yuidoc

YUI Doc is a tool written in Python that generates beautiful, organized, searchable API documentation for your JavaScript code. You will typically use YUI Doc as part of your build process. YUI Doc is comment-driven and is compatible with a variety of coding styles. You do not need to be using YUI Library JavaScript in order to use YUI Doc.

MS Visual Round Trip Analyzer

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=119F3477-DCED-41E3-A0E7-D8B5CAE893A3&displaylang=en

The Visual Round Trip Analyzer tool helps web developers and testers visualize the download of their page, identify best practices and changes that improve web performance. The network Round-Trip between the client and server(s) is the single biggest impact to web page performance – much greater than server response time. VRTA examines the communications protocol, identifying the causes of excessive round-trips, and recommending solutions. Performance engineers, testers, developers, operations personnel should use VRTA to conduct their web performance analysis.

HTTP Scoop

http://www.tuffcode.com/index.html

HTTP Scoop passively listens for HTTP requests from any browser (or other application for that matter) running on your Mac.

There’s no special configuration needed, no cumbersome proxies required. You just hit the Scoop button and off you go.

  • Capture HTTP conversations
  • View headers, parameters & more
  • View & save responses
  • Any browser/client or server
  • No proxy or browser plug-in
  • Great for AJAX and Web Services

Web tools

These are tools that you use directly on the code or an URL to test your web sites /apps.

Boomerang

http://yahoo.github.com/boomerang/doc/

Boomerang is a piece of javascript that you add to your web pages, where it measures the performance of your website from your end user’s point of view. It has the ability to send this data back to your server for further analysis. With boomerang, you find out exactly how fast your users think your site is. All you have to do is stick it into the bottom of your web pages and call the init() method.

Boomerang is opensource and released under the BSD license.

YUI Profiler

http://developer.yahoo.com/yui/profiler/

The YUI Profiler is a simple, non-visual code profiler for JavaScript. Unlike most code profilers, this one allows you to specify exactly what parts of your application to profile. You can also programmatically retrieve profiling information as the application is running, allowing you to create performance tests YUI Test or other unit testing frameworks.

Perfectomobile

http://www.perfectomobile.com

Test Mobile Applications on Real Devices.

The Perfecto Mobile Handset Cloud system enables you to access and control real mobile devices via the web. Using the system you can quickly and easily operate the phone keys, touch-screen, or QWERTY keyboard to control the device, install applications on the device and verify that your application or service works properly and displays correctly on the phone’s screen.

The Perfecto Mobile system is a hardware and software solution. The mobile handset is mounted on a cradle that holds it in a specific location. A video camera, located in front of the handset’s screen, captures the real user experience as it is displayed on the handset’s screen.

  • Controlling a remote device
  • Typing Text.
  • Installing an application on the handset
  • Keep a record of your actions and collaborate
  • Screen Shots.
  • Video Clips.
  • On-Line.
  • Testing interruptions.
  • Sending SMS.
  • Web-based UI.

The members of the Opera Developer Network get 7 hours of remote access, free of charge.
http://www.perfectomobile.com/portal/cms/opera.xhtml?key=OP631R89YL2

Web Page Test

http://www.webpagetest.org/

WebPagetest is a tool that was orginially developed by AOL for use internally and was open-sourced in 2008. The online version at www.webpagetest.org is an industry collaboration with various companies providing the testing infrastructure for testing your site from across the globe.

JSLint

http://www.jslint.com/

JSLint is a JavaScript program that looks for problems in JavaScript programs. It is a code quality tool.

Minification is the process of eliminating white space, comments, and other nonessential parts of the javascript code to decrease the size of the JS files that need to be transfered from the server to the browser.

YUI Compressor

http://yuilibrary.com/projects/yuicompressor/

YUI Compressor is an open source tool that supports the compression of both JavaScript and CSS files. The JavaScript compression removes comments and white-spaces as well as obfuscates local variables using the smallest possible variable name. CSS compression is done using a regular-expression-based CSS minifier.

Google Closure Compiler

http://code.google.com/intl/es-AR/closure/compiler/

The Closure Compiler reduces the size of your JavaScript files and makes them more efficient, helping your application to load faster and reducing your bandwidth needs.

The Closure Compiler provides warnings for illegal JavaScript and warnings for potentially dangerous operations, helping you to produce JavaScript that is less buggy and and easier to maintain.

The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what’s left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.

To help you work with your transformed code, you can also install the Closure Inspector, a tool that makes it easy to use the Firebug JavaScript debugger with the Compiler’s output.

The Closure Compiler has also been integrated with Page Speed, which makes it easier to evaluate the performance gains you can get by using the compiler.

Conclusion

Web performance monitoring and analysis tools can provide a lot of knowledge about how your end-users uses the website or web app from different perspectives, so it is very important to know the tools that we have to measure different parts of the applications.

Pies de página ajustables multi pantalla

noviembre 12, 2010 Deja un comentario

Hace unos días, navegando vi una tecnica para ajustar el pie de página en diferentes pantallas, busque la liga pero no la encontré de todas maneras aqui la comparto porque es un buen tip para hacer pies de página que se ajusten a cualquier tipo de pantalla usando css,

Se crea un documento html con un div que va a ser el pie de la pagina y se le asigna la clase pie:

<div class=”pie”>
<p>
<a href=”#”>Liga 1</a>&nbsp;
<a href=”#”>Liga 2</a>&nbsp;
<a href=”#”>Liga 3</a>&nbsp;
<a href=”#”>Liga 4</a>
</p>
</div>

La clase css pie para que se ajuste a cualquier pantalla es:

.pie {

width:100%;
height:40px;
left:0px;
position:absolute;
top:100%;
margin-top:-40px;

}

Lo interesante son las ultimas 2 líneas  al establecer el top al 100%, el div se ajustará al final del documento desapareciendo, y al ajustar el margen superior negativo del mismo alto que el div se ajustrará siempre al final del documento.

Técnicas y estrategias para el diseño de sitios multi-dispositivo. (moviles)

noviembre 8, 2010 2 comentarios

Hoy en día cuando se desarrolla una aplicación web, se debe tener en cuenta que puede ser visitada desde diferentes medios.

Al diseñar un sitio multi-dispositivo, se debe considerar cuales funciones y características se van a mostrar en cada tipo de dispositivo, suponiendo que estos varían, se va a requerir alterar el formato emitido por el servidor.

Debido a que existen numerosos dispositivos y dentro de estos existen numerosas versiones (versión del OS, navegador, html, css, js), se generan numerosas combinaciones que son un dolor de cabeza para los desarrolladores Web. Hoy en día, de las principales tareas en el desarrollo de un sitio web son la detección de las capacidades del medio y la detección del medio.

La detección de medio permite la identificación  de las propiedades y características de un dispositivo, con el propósito de determinar el mejor contenido, diseño, markup o aplicación a servir hacia el dispositivo, permite a los desarrolladores identificar funciones y características como tamaño de pantalla, tipo de navegador (o versión), si soporta video y audio, nivel de soporte de CSS, HTML y JS.

Identificación de medio por Bases de datos de dispositivos.

Cuando se desarrolla sitios, tarde o temprano se necesita saber que dispositivo está usando el usuario, es inevitable, todos los dispositivos son diferentes y para ofrecer una gran experiencia móvil se necesitan conocer las capacidades específicas de cada dispositivo. Entre más refinada se necesite la segmentación de un sitio web, se necesitará hacer algo más que checar las palabras clave en las cabeceras HTTP.

Actualmente, la mejor forma para detección de dispositivos es por medio de bases de datos de dispositivos,  como DeviceAtlas o Wurfl.

Estas bases de datos pueden ayudar a conocer todas las propiedades generales del dispositivo (así como proveer ajustes más finos dentro de los grupos que se definan con capacidades específicas). Estas base de datos tienen grandes conjuntos de datos con los tamaños de pantalla.

WURFL

WURFL está basado en el concepto de familias de dispositivos. Todos los dispositivos son descendientes de un dispositivo genérico, pero pueden también descender de familias más especializadas, este mecanismo llamado ‘fall_back’, permite a los desarrolladores derivar las capacidades de un teléfono buscando las capacidades de su familia, a menos que una cierta característica sea específicamente diferente para ese teléfono. Ver post anterior sobre WURFL.

Device atlas.

Device atlas es una solución para detección de dispositivos y contiene datos de más de 6,000 dispositivos. Se utiliza por medio de un API que provee device atlas y soporta PHP, Java, .NET, Ruby y Python. Para más información visitar: http://deviceatlas.com/get-started

Identificación de propiedades de dispositivo con  media queries.

CSS-3 mejora el soporte para los CSS que son dependientes al medio, y permite seleccionar las hojas de estilo de manera más precisa utilizando los media queries.

Los media queries  se usan del lado del cliente, y son muy útiles porque  permiten que el contenido se adapte a un rango específico de dispositivos de salida sin necesidad de tener que cambiar el contenido en sí. Se pueden usar para ajustar el diseño y el estilo de una página una vez que se carga en el dispositivo.

Un media query consiste de un tipo de medio y cero o más expresiones que comprueban  las condiciones de las características particulares del medio como ancho, alto o color. Las expresiones lógicas resuelven verdaderas o falsas. Por ejemplo

<link rel=”stylesheet” media=”screen and (max-device-width: 360px)” href=”ejemplo.css” />

Esto será verdadero para tipos de medio que sean screen y que tengan como ancho máximo 360px

El resultado de la expresión es verdadero si el tipo de medio especificado en el media query cumple con el tipo de dispositivo en donde el documento está siendo visto y todas las expresiones del media query son verdaderas.

Cuando el media query es verdadero, el CSS correspondiente es aplicado siguiendo las reglas de la hoja de estilo.

Se pueden crear consultas complejas usando operadores lógicos (not, and, only), así como combinar varios media queries en una lista separada por comas, si una consulta de la lista es verdadera entonces la hoja de estilos asociada es aplicada, es el equivalente al operador “or”.

El operador not, niega el resultado de la consulta “all and (not color)” es verdadera para dispositivos monocromáticos sin importar el tipo de medio.

El operador only, esconderá las hojas de estilo para navegadores antiguos que no soporten media queries.

<link rel=”stylesheet” media=”only screen and (color)” href=”ejemplo.css” />
Esto será verdadero para tipos de medio screen y que sean de color.

Los media queries no son sensibles a las mayúsculas y los paréntesis son requeridos para las expresiones.

Un problema que tienen es que su uso es vago en dispositivos de nivel medio / bajo, por lo que se debe de utilizar Progressive enhancement (seguir leyendo) de una manera que se degrade elegantemente el sitio.

Otro problema es que los media queries solo permiten manipular el estilo y tienen poca influencia sobre lo que se descargue al dispositivo, no pueden manipular el html por lo que se debe confiar en las reglas de CSS para por ejemplo cambiar el tamaño de las imágenes para que se adapten  al dispositivo.

Estrategias para servir contenido a diferentes dispositivos.

Existen diferentes técnicas para servir contenido en pantalla, además dependiendo del medio, existen API’s que facilitan estas acciones.

Progressive enhancement (mejora progresiva).

Una técnica muy común es desarrollar primero para navegadores antiguos y móviles (con menos capacidades que los modernos o de escritorio) y usar Progressive enhancement (mejora progresiva) para servir el contenido que soporte el dispositivo. Se pueden usar media queries y javascript para lograrlo. Una buena explicación de  Progressive enhancement se puede leer en la siguiente liga. http://www.alistapart.com/articles/understandingprogressiveenhancement/

Redirección de sitio.

Otra técnica es la redirección a otro dominio (o subdominio), dependiendo del medio que se detecte se reenvía a otro URL especifico para el dispositivo. Generalmente se usa por medio de la detección del agente de usuario o alguna librería de dispositivos del lado del servidor.

Plantillas.

Otra técnica es el uso de plantillas para familias de dispositivos, se agrupan capacidades de dispositivos en familias, dependiendo de las capacidades del medio que se detecten, se identifica la familia a la que corresponde y se muestra la plantilla. Se puede utilizar media queries, javascript o alguna librería de dispositivos del lado del servidor.

Algoritmos.

Es una técnica que usa algoritmos para cambiar el contenido van adaptando el contenido de manera apropiada para cada dispositivo. Generalmente se usa javascript.

Técnicas para cuidar el  rendimiento en la detección de dispositivos.

Es importante considerar el rendimiento en las aplicaciones Web. Detectar el dispositivo o las capacidades del medio en cada página que se visite de un sitio web no se considera como buena práctica porque afecta el rendimiento de la aplicación al estar realizando la misma tarea repetitivamente, para ayudar a mejorar el rendimiento, se realiza la detección en la primer visita y en las demás accesos solo se consulta la información que se guardó.  Algunas técnicas son:

Cookies de propiedades.

Para los dispositivos que aceptan cookies, una buena técnica es crear una cookie por medio de javascript, en esta cookie se almacenan las propiedades del medio de donde se está viendo la aplicación web, como por ejemplo ancho y alto de pantalla, y además se puede almacenar sus capacidades como por ejemplo si acepta xhr, canvas, flash ó localización.
La cookie se consulta por medio de la aplicación para proveer contenido adecuado al dispositivo,  y adaptarlo. Adicionalmente se puede combinar esta información con alguna base de datos para conocer características adicionales del dispositivo en caso de que sea necesario y formatear el contenido antes de enviarlo al dispositivo.

Los pasos generales son:

  1. Crear un objeto JS donde se guarda las propiedades y características que se necesitan en la aplicación.
  2. Cifrar el objeto en una cadena JSON y guardarlo en una cookie.
  3. Para cargar los datos de la cookie se descifra la cadena JSON de nuevo en un objeto JS.

Esta técnica funciona muy bien cuando se guarda poca información.
Un problema puede ser que si el navegador de donde se consulta no acepta cookies o las tiene desactivadas no funcionará así como tampoco si tienen javascript desactivado. Esto debido a que esta técnica se basa completamente en cookies y en javascript. Una solución a este problema es combinarlo con media queries o detección del lado del servidor, para conocer si acepta javascript y cookies.

Frames / iFrames.

Esta técnica se utiliza creando dos Frames, un Frame informativo, y otro Frame que se utiliza como navegación, este frame es el que se actualiza y en donde se generan todas las peticiones. Las propiedades y características del medio se guardan en un objeto javascript en el frame informativo. Esta técnica funciona también con iframes.
Un problema de este acercamiento es que el uso de frames no es una buena práctica en algunos dispositivos, además que no son soportados (o están desactivados) por algunos navegadores.

Web Storage (Almacenamiento Web).

Para navegadores que acepten HTML5 existe una característica que se llama Web Storage que es una especificación que define una API para el almacenamiento de datos (clave-valor) en los clientes Web. Este acercamiento es muy similar al de Cookies de propiedades pero usando un objeto nativo del navegador llamado localStorage.
Una ventaja es que acepta más tamaño de almacenamiento que las cookies. La desventaja es que solo se puede usar en navegadores modernos.

Recomendaciones para el desarrollo de sitios multi-dispositivos.

La meta de una aplicación multi-dispositivos o multi-pantalla no es necesariamente que se vea idéntica en cada dispositivo, más bien que se adapte a cualquier dispositivo.

Pensando en términos de  multi-dispositivo, se debe tomar en cuenta la experiencia de usuario del dispositivo (touch, track ball, track pad, teclado, etc) y asegurarse de que los elementos clickeables sean adecuados a la forma de navegación (los botones en ambientes touch sean suficientemente grandes para pulsarse).

Pensando en términos de multi-pantalla, se debe ajustar dinámicamente a la resolución y PPI del dispositivo en el cual se está viendo, desplegando más información en pantallas grandes, y removiendo o encogiendo elementos en pantallas pequeñas.

Para que las aplicaciones funcionen en diferentes pantallas, se deben diseñar de tal manera que se dibujen a sí mismas en el momento adecuado y con las restricciones adecuadas.

Siempre se debe de programar con código bien estructurado.

Para que se cargue rápido la aplicación se debe comprimir el contenido cuando y donde sea posible.

Se debe evitar el envío de datos innecesarios.

Al agrupar dispositivos por tamaño de pantalla, se debe considerar el markup que soporta, capacidades, método de interacción y más, todo depende del tipo de sitio.

Mantener un balance entre la accesibilidad, las capacidades, experiencia de usuario, usabilidad, funcionalidad, rendimiento y ancho de banda.

JavaScript Patterns by Stoyan Stefanov

noviembre 3, 2010 Deja un comentario

JavaScript Patterns by Stoyan Stefanov

This book is really awesome, from the beginning to the end, the author shows useful tools to improve the javascript programming.

With more than 30 patterns the author goes from basic concepts, such as avoiding globals, using single var declarations, precaching length in loops, following coding conventions, running JSLint, etc., to advanced ones like variable hoisting, select algorithms at runtime, proxy objects, loading strategies, javascript optimization and a lot of more.

What I liked about the book was the way in which the author explains and illustrates the patterns and how well organized the book is written, this book helped me to understand in a better way some javascript techniques with several solutions to a common scenarios.

I recommend this book if you want to write better code, if you want to understand how the libraries are written or if you want to write your own javascript library. It helps a lot to understand the javascript core and the fundamentals and helps also to be more productive taking care of performance and maintenance of javascript code.

You can buy from O’Reilly

http://oreilly.com/catalog/9780596806767/

or from amazon

http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752/

I review for the O'Reilly Blogger Review Program

Categorías:AJAX, javascript Etiquetas:

Aplicaciones Web Offline con el archivo manifest de HTML5 (Offline Application Cache)

octubre 6, 2010 5 comentarios

Existe una característica en HTML5  llamada Offline Application Cache que permite a los usuarios correr aplicaciones Web aun y cuando no estén conectados a Internet. Funciona de la siguiente manera:

Cuando un usuario visita una aplicación Web, el navegador descarga y guarda todos los archivos necesarios para desplegar la página (HTML, CSS, javascript, imágenes, etc).

La siguiente vez que el usuario visita la aplicación, el navegador reconoce la dirección y sirve los archivos del cache de la aplicación local, en lugar de obtenerlos por la red.

El principal componente de esta característica se llama archivo de manifiesto (manifest file), que es un archivo de texto que se guarda en el servidor Web. Este archivo se envía al dispositivo del usuario y su tipo mime es cache-manifest.

Este archivo contiene una lista de archivos que el dispositivo del usuario debe descargar y guardar para que funcione la aplicación.

Ejemplo.

Por ejemplo supongamos una página HTML que se usa de splash para correr una aplicación la estructura de archivos sería la siguiente:

index.html

_img/splash.png

_js/index.js

_css/index.css

app.manifest

Los pasos para utilizar esta característica (Offline Application Cache)

1. Crear un cache manifest.

El archivo app.manifest tendrá las referencias a todos los recursos que queremos guardar en el cache de la aplicación:

Contenido de app.manifest:

CACHE MANIFEST
#Cache para la aplicación que no tenga conexión de red
#V1
#Archivos HTML
index.html
#Archivos javascript
_js/index.js
#Archivos CSS
_css/index.css
#Imagenes
_img/splash.png

Las rutas son relativas al archivo (también se pueden usar rutas absolutas), las líneas que comienzan con # son comentarios.

2.  Referenciar el archivo cache.

Para que se tenga acceso offline y funcione la aplicación con los archivos específicos en el archivo se necesita ligarlo, agregando un atributo manifest a la etiqueta de html dentro del index.html.

<html manifest=”app.manifest”>

Se debe configurar el tipo mime correcto (text/cache-manifest) en el servidor Web, porque si no, el navegador no lo va a reconocer.

En apache, el archivo mime.types se encuentra en el fólder /conf/ al final del archivo se escribe:

#HTML5 applicacion cache_offline access

text/cache-manifest manifest

Si no se tiene acceso a esa carpeta entonces se crea un archivo .htaccess en el directorio Web con la siguiente línea:

AddType text/cache-manifest .manifest

Con esto la aplicación debe funcionar correctamente, la segunda  vez que un usuario visite la aplicación, los recursos listados en el archivo se descargaran localmente de su dispositivo. (Móvil o desktop).

Actualizando el archivo.

Cuando el usuario visita el sitio, el navegador compara los archivo manifest (local y remoto) y checa si son iguales, si el archivo remoto cambió, el navegador descarga todos los archivos listados en el.

La comparación del contenido de los archivos se realiza byte por byte (incluyendo comentarios y líneas vacías), el cambio de alguno de los archivos listados en el manifest es irrelevante para determinar si se hizo algún cambio o no.

Hay que tomar en cuenta que cuando se actualiza un archivo, la descarga de los nuevos archivos se hace en el fondo, después de que se cargó la web app. Esto significa que incluso después de descargar los nuevos archivos, el usuario seguirá trabajando con los archivos viejos. Los archivos nuevos que fueron descargados en el fondo, no serán visibles hasta que el usuario vuelva a lanzar la aplicación. (leer mas adelante la solución a esto).

También es posible forzar al navegador a cargar ciertos recursos de la red siempre, por medio de la instrucción NETWORK,  por ejemplo si quisiéramos que una imagen siempre sea solicitada del servidor web, dentro del archivo manifest se declara de la siguiente manera

NETWORK:
imagen.jpg

El problema de esto es que si la aplicación se corre cuando no hay conexión, la imagen se tratara de cargar desde el servidor, para solucionar esto se puede utilizar otra instrucción para especificar que si no existe conexión se cargue un archivo local, y si hay se cargue el archivo desde el servidor.

En lugar de la instrucción NETWORK se utilizaría FALLBACK de la siguiente manera:

FALLBACK
imagen.jpg imagenLocal.jpg

Cuando el usuario tenga conexión la aplicación solicitará al servidor imagen.jpg y cuando no tenga usará la imagen del cache (imagenLocal.jpg).
También se puede especificar una sola imagen para mostrar cuando la aplicación este sin conexión, en lugar de todas las imágenes que se muestran en la aplicación.

FALLBACK
_img/ _img/imagenLocal.jpg

Objeto applicationCache.

Como ya expliqué, cuando un usuario visita una página que tiene un archivo manifest, el navegador trata de comparar o actualizar el cache, lo hace comparando los archivos (local y del servidor). Si los archivos son diferentes, se descargan los recursos y se almacenan de nuevo.

Mientras esto pasa, varios eventos se disparan en un objeto llamado ApplicationCache, con este objeto por ejemplo podemos actualizar al usuario con los nuevos archivos descargados,  sin necesidad de volver a lanzar  la aplicación.

API.

cache = window.applicationCache

Regresa un objeto ApplicationCache del documento activo de la ventana.

cache.status

Regresa el código de estatus actual del objeto con las siguientes constantes:

0 : uncached

1 : idle

2 : checking

3 : downloading

4 : updateready

5 : obsolete

cache.update()

Invoca el proceso de descarga de cache, arroja una excepción  de tipo INVALID_STATE_ERR en caso de que no exista cache para actualizar.

cache.swapCache()

Cambia el cache mas reciente en caso de que exista uno, si no, arroja una excepción de tipo  INVALID_STATE_ERR

Ejemplo.

Para actualizar la aplicación con los archivos nuevos sin recargar la aplicación:

Window.applicationCache.addEventListener(‘updateready’, function(){
Window.applicationCache.swapCache();}, false);

Esta característica es muy importante para el futuro de las aplicaciones Web móviles, el limite en iphone al parecer es de 5mb, en los demás dispositivos (Android, blackBerry, Palm) aun no lo he encontrado.

Seguir

Get every new post delivered to your Inbox.