Categorías
Citas ECMAScript

El objeto this en ECMAScript

Uno de los grandes misterios de ECMAScript desvelado 🙂

We said earlier that this is not an author-time binding but a runtime binding. It is contextual based on the conditions of the function’s invocation. this binding has nothing to do with where a function is declared, but has instead everything to do with the manner in which the function is called.

When a function is invoked, an activation record, otherwise known as an execution context, is created. This record contains information about where the function was called from (the call-stack), how the function was invoked, what parameters were passed, etc. One of the properties of this record is the this reference which will be used for the duration of that function’s execution.

You Don’t Know JS: this & Object Prototypes — Leslie Zhang

Y qué decir de los libros de la serie You don’t know JS: muy recomendables.

Categorías
Citas Desarrollo web ECMAScript

DOM vs. todo lo demás

Como ya he comentado alguna vez, no estoy precisamente a la última en las nuevas tendencias de desarrollo web (¿?). Cuando empecé en esto, Netscape 4 era mayoritario, y empezaba a manifestarse una guerra de navegadores frente a Internet Explorer.
Obviamente todo ha cambiado mucho: ordenadores, navegadores, pantallas, soporte de estándares, velocidad de conexión, las librerías de javascript, los frameworks web, los móviles, y ese mundo inabarcable en el que se está convirtiendo todo lo relacionado con el desarrollo web: npm anuncia 475.000 building blocks ahora mismo.
Lo raro es no tener fatiga de desarrollo web y javascript. Lo normal es sufrir ansiedad porque es imposible estar al día.

Terminado el inciso pseudohistórico y de salud mental, y antes de la cita del 2015 que quería incluir, me gustaría dejar apuntadas algunas reflexiones no muy elaboradas, pero que merecen tenerse en cuenta:

  1. Cada bloque de código y fichero que se incluye en una página web, implica un aumento del tiempo de carga: ya sea una imagen, o una hoja de estilos. Cada kilobyte cuenta.
  2. Cada nodo que se añade al DOM, es un elemento más a tener en cuenta para el motor de renderizado del navegador.
  3. Cuando usamos una librería que trabaja con el DOM o una abstracción del mismo, implica que se incrementa el número de eventos que están a la espera aunque no se utilice. Afecta al rendimiento (tiempo de carga, uso de memoria,…). Yo desde hace años tengo la imagen mental de un frasco lleno de avispas nerviosas 🙂
  4. Cada nueva librería, plugin,… añade complejidad y posibles problemas de compatibilidad.
  5. La dependencia en el desarrollo de wadus-script junto un equipo de desarrollo con más o menos conocimiento específico, puede tener un alto coste si hay que reemplazarlo.

Claro, que también se puede ver desde el siguiente punto de vista:

  1. Hay código y ficheros de una página web, que valen su peso en oro.
  2. Algunos elementos extra de HTML, identificadores o clases pueden ser muy útiles (aunque todavía no lo sepamos).
  3. Hay librerías que simplifican mucho el tiempo y la eficiencia en el desarrollo.
  4. Al igual que en el punto anterior, hay librerías que pueden simplificar el desarrollo e incluso solucionar problemas de compatibiliad (como html5shiv o es5-shim).
  5. El uso del wadus-script de turno por un equipo competente, puede tener resultados brillantes.

Por lo tanto, depende es una palabra clave ante estas cuestiones. Al final el factor determinante debería ser el proyecto a desarrollar y el rendimiento (en tiempo de carga, tiempo hasta que se puede interactuar, tiempo de desarrollo, calidad de código y facilidad de mantenimiento,…).

La teoría, en ocasiones es sencilla 🙂

Y ahora, la cita en cuestión.

The DOM Is Just Fine

It puzzles me that developers seem to create themselves a problem and then they point the finger around to search and blame the cause: no, the DOM is not your problem, the fact you brought an over-engineered abstraction on top of a deadly simple task, like a table that needs some quick update, is the real problem you don’t want to see.
It scares me that developers behind frameworks seem to be often incapable of getting some fresh air and think out of the cell they put themselves in: learning and using only that framework, ignoring everything else … sometimes forgetting even common sense, probably shadowed by the framework approach.
Let’s do ourselves a favor, let’s stop being religious about any sort of framework and learn what the native world has to offer, what other frameworks have to offer too, and what’s the best solution for that specific problem, which is never every problem we have!
Every framework was born to solve a very specific problem … have you asked yourself if that is really the same problem you have and the one you need to solve?
Moreover, there will always be a faster, ad-hoc, way to do this or that and your framework cannot cover all the cases … it’s actually the opposite: the more cases it will cover, the slower it will be. So let’s please stop moaning about the DOM and start doing things in a different way … shall we?
We’ll be those with most benefits, after all, so please think about it.

The DOM Is NOT Slow, Your Abstraction Is Andrea Giammarchi

Categorías
Citas Desarrollo web ECMAScript

IndexedDB

Estaba mirando la especificación de Indexed Database API (especificación del W3C desde el 2015), pero gracias al siguiente tutorial, me he enterado mucho mejor. Y aquí lo dejo.

A website can have one or more IndexedDB databases. Each database must have a unique name.

A database can contain one or more object stores. An object store, which is also uniquely identified by a name, is a collection of records. Each record has a key and a value. The value is an object that can have one or more properties or attributes. The key can be based on a key generator, derived by a key path, or explicitly set. A key generator automatically generates a unique sequential positive integer. A key path defines the path to the key value. It can be a single JavaScript identifier or multiple identifiers separated by periods.

The specification includes both an asynchronous and a synchronous API. The synchronous API is meant to be used within web workers. The asynchronous API uses requests and callbacks.

Brian StewartUsing the HTML5 IndexedDB API

Categorías
Citas Desarrollo web Libros

Sugerencias para mejorar el peso y rendimiento de las páginas webs

Acabo de leer el —brevísimo— libro Web Page Size, Speed, and Performance, escrito por Terrence Dorsey y publicado por O’Reilly (la descarga es gratuíta).
El contenido del libro, como podrás imaginar, consta de consejos para mejorar el peso y rendimiento de una página web. Y creo que cada vez hay que valorar más aspectos como el peso y el rendimiento, teniendo en cuenta la tendencia actual. Cualquier «doctor web» nos diría hay un evidente sobrepeso.
Se puede encontrar una cita cuyo origen está en el mundo de la automoción, aplicable perfectamente al desarrollo web:

Simplify, then add lightness.

Collin Chapman

Sugerencia: puedes aprovechar para procasti…, digo, para ampliar tus bastos conocimientos leyendo un poco sobre Collin Chapman y la empresa de coches que fundó, Lotus.
Continuando, si es que se puede, en el libro aparecía un colofón con unos cuantos consejos, que cito a continuación:

  1. Start by measuring the size, request latency, and load time of your current site on various devices. You can do this right in the browser.
  2. Use online tools to measure more advanced site performance metrics and compare them against industry average.
  3. Know how long your page takes to finish rendering and what the time is to the first interaction. This is your first-impression metric.
  4. Evaluate your business goals and try to correlate site performance with traffic, conversiones, revenues, or whatever metrics is relevant to your business.
  5. Count all of the components that have to be requested to render your page Can you reduce this number?
  6. Slim down your HTML. Combine and minfiy your CSS files.
  7. Take a close look at where you reference scripts and when they excecute. Are scripts blocking page rendering or interaction?
  8. Make sure you’re using images wisely and optimizing them for size and quality. A little bit of code can make sure you’re not sending too many image bytes where they’re not needed.
  9. Don’t throw out social features just because they add to your request, scripts, and page size if they benefit the business; just be sure to use them tactically instead of spreading them all over the place.
  10. Starting with a focus on the mobile experience —most likely your fastest growing customer experience— may help you target performance optimizations that benefit all visitors to your site, even those using the desktop.
Categorías
Accesibilidad web Citas

La accesibilidad web es ley desde hoy en Europa

Ya desde enero de 2010 los sitios web creados en Europa deben cumplir con las WCAG 2.0 (As from January 2010, all new EUROPA websites have to be created in compliancy with the Web Content Accessibility Guidelines 2.0, level AA.) y en 2015 se publicó la ley europea de accesibilidad, pero ayer, tres de mayo de 2016 se llegó a un acuerdo entre el Parlamento, el Consejo y la Comisión; para que todos los sitios del sector público y sus aplicaciones móviles cumplan con una serie de requisitos (unas normas técnicas) y, además, sean monitorizados.

—Emmanuelle Gutierrez y Restrepo

El Comunicado de Prensa de la Comisión Europea con la noticia original: La Comisión, satisfecha del acuerdo para una mayor accesibilidad de los sitios web y las aplicaciones del sector público.