Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Front-end: Diseñar webs rápidas, flexibles y potentes

Manz
July 15, 2015

Front-end: Diseñar webs rápidas, flexibles y potentes

Presentación de la conferencia "Front-end: Diseñar webs rápidas, flexibles y potentes" impartida en la Tenerife LAN Party 2015.

Herramientas y consejos de front-end relacionados con HTML5 (Jade, LenguajeHTML.com, MinifyHTML, API HTML5...), CSS3 (LESS, LenguajeCSS.com, autoprefixer, cssnext, uncss...), SVG, Javascript (Babel, d3, Coffeescript, jQuery...), datos ligeros (XML, JSON, YAML), editores web y task runners (GulpJS).

Más información relacionada:
http://www.emezeta.com/articulos/10-pasos-para-renovar-el-front-end-del-blog
http://lenguajehtml.com/
http://lenguajecss.com/
http://lenguajejs.com/

Manz

July 15, 2015
Tweet

More Decks by Manz

Other Decks in Programming

Transcript

  1. > back-end > servidores web Apache, nginx, LiteSpeed... > bases

    de datos MySQL, PostgreSQL, MongoDB... > lenguajes PHP, NodeJS, Python, Ruby, Java...
  2. > front-end > Lenguaje HTML Estructura y contenido web >

    Lenguaje CSS Diseño y aspecto visual
  3. > front-end > Lenguaje HTML Estructura y contenido web >

    Lenguaje CSS Diseño y aspecto visual > Lenguaje JS Programación web en front-end
  4. > Hay 3 formas de hacer una web Hacer que

    Chuck Norris se sienta orgulloso de nosotros
  5. > Fragmentación web En un navegador se ve genial, pero

    cuando intentamos verlo en otro...
  6. > objetivos > Rápida Debe cargar lo más rápido posible.

    > Flexible Debe ser fácil de mantener.
  7. > objetivos > Rápida Debe cargar lo más rápido posible.

    > Flexible Debe ser fácil de mantener. > Potente y eficiente Usar los recursos a tu alcance.
  8. > HTML5 <div id="panel"> <h3>Selecciona tu opción:</h3> <select id="tipo" class="flat">

    <option value="1">Opción #1</option> <option value="2">Opción #2</option> <option value="3">Opción #3</option> </select> </div> lenguajehtml.com
  9. > Minificación de código Objetivo: Reducir el peso del archivo.

    Minify, Uglify (minificadores) Prettify, Beautify (desminificadores)
  10. > Minificación de código <div class="text"> <h3>Información</h3> <a href="http://twitter.com/Manz">@Manz</a> <a

    href="http://www.emezeta.com/">Web</a> </div> ... <div class="text"><h3>Infor mación</h3><a href="http:// twitter.com/Manz">@Manz< /a><a href="http://www.eme zeta.com/">Web</a></div> ... 11KB 32KB
  11. > Minificación de código - Eliminar (colapsar) espacios y/o saltos

    de línea. - Eliminar comentarios. - Reducir código (borrar redundancias, usar alternativas...). - Reagrupar selectores CSS. - Redondear unidades a “X” decimales. Objetivo: Reducir el peso del archivo. Minify, Uglify (minificadores) Prettify, Beautify (desminificadores)
  12. > npm install -g html-minifier > html-minifier index.html --minify-css --minify-js

    --remove-script- type-attributes --remove-style-link-type- attributes --use-short-doctype --remove- comments --collapse-whitespace -o index.min.html > cat index.html | html-minifier > Minificación HTML Minifica el CSS o el JS “inline” (requiere cleancss / uglifyjs) Elimina atributos “type” o simplifica DocType (HTML5) Elimina los comentarios HTML del documento Elimina (colapsa) los espacios en blanco del HTML
  13. > Selectores CSS div#info div.flat ul.links a <div id="info">Info</div> <div

    class="flat">...</div> <ul class="links"> <li> <a href="#link">enlace</a> </li> </ul>
  14. > EMMET select#tipo>option[value=$]{Opción #$}*3 bit.ly/emmetcheat <select id="tipo"> <option value="1">Opción #1</option>

    <option value="2">Opción #2</option> <option value="3">Opción #3</option> </select> TAB
  15. > HAML #panel %h3 Selecciona tu opción: %select#tipo.flat %option{:value =>

    "1"} Opción #1 %option{:value => "2"} Opción #2 %option{:value => "3"} Opción #3 haml.info
  16. > JADE #panel h3 Selecciona tu opción: select#tipo.flat option(value='1') Opción

    #1 option(value='2') Opción #2 option(value='3') Opción #3 jade-lang.com
  17. > JADE include info.include.jade - var title = "Selecciona tu

    opción" #panel h3= title select#tipo.flat ul each val in [1, 2, 3] option(value=val) Opción ##{val} jade-lang.com Incluir código HTML de forma muy organizada. Variables personalizadas con contenido. Estructuras de control, bucles o facilidades.
  18. > emezeta.com DNS Conexión SSL Subida Espera Descarga Dominio Alojamiento

    Contenido html Redirección Backend ¿Depende del usuario? Se puede optimizar
  19. > Velocidad > Fuente: Google Analytics Dominio Conexión Redirección Respuesta

    Descarga Total Restante 0,02s 0,10s 0,24s 0,30s 0,15s 5,69s 4,88s Dominio Alojamiento Web
  20. CSS html PNG PNG JPG JPG JS > esto ocurre

    por cada recurso de la web al principio al final
  21. > Pingdom Tools > Google PageSpeed > Web Page Test

    http://tools.pingdom.com/fpt/ https://developers.google.com/speed/pagespeed/ http://www.webpagetest.org/
  22. > WebFonts > No pierden resolución al ampliar/reducir > Son

    fuentes, puedes tratarlas con CSS > Desventaja: Sólo un color > Desventaja: Quiero un icono específico
  23. > curl -L -H Accept-encoding:gzip -I emezeta.com HTTP/1.1 200 OK

    Server: nginx Date: Thu, 02 Jul 2015 03:28:17 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 20 Connection: keep-alive Vary: Accept-Encoding Content-Encoding: gzip > ¿Usa compresión HTTP? El sitio web comprime en gzip los documentos Sólo algunos formatos pueden usar compresión HTTP: html, json, css, js, xml, svg... Pregunto si el sitio web soporta compresión HTTP
  24. > npm install -g imagemin [email protected] postinstall √ gifsicle pre-build

    test passed successfully [email protected] postinstall √ jpegtran pre-build test passed successfully [email protected] postinstall √ optipng pre-build test passed successfully [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ... > Optimización de imágenes
  25. > ls -lh image.png -rw-r--r-- Manz 447k image.png > imagemin

    image.png > ls -lh build\image.png -rw-r--r-- Manz 369k image.png > Optimización de imágenes
  26. > npm install -g jpgo > jpgo image.jpg 䘠 image.jpg

    before=153.6 kB after=144.93 kB reduced= 8.67 kB > Optimización de imágenes
  27. > CSS3 button.flat { border: 0; border-radius: 25px; padding: 10px;

    background: RGBA(0,0,0, 0.5); color: white; transition: all 2s ease-in-out; } button.flat:hover { background: #A00; cursor: pointer; transition: all 1s ease; } lenguajecss.com
  28. #contenedor { border: 4px solid white; padding: 10px; display: flex;

    } .item { width: 25px; } .item-1 { background: red; order: 1 } .item-2 { background: green; order: 2 } .item-3 { background: blue; order: 3 } 1 2 3 > FlexBox
  29. #contenedor { border: 4px solid white; padding: 10px; display: flex;

    } .item { width: 25px; } .item-1 { background: red; order: 3 } .item-2 { background: green; order: 2 } .item-3 { background: blue; order: 1 } 3 1 2 > FlexBox
  30. #contenedor { border: 4px solid white; padding: 10px; display: flex;

    flex-direction: column; } .item { width: 25px; } .item-1 { background: red; order: 3 } .item-2 { background: green; order: 2 } .item-3 { background: blue; order: 1 } > FlexBox 3 1 2
  31. img { border: 2px solid white; width: 300px; margin: .4em;

    } .original { } .sepia { filter: sepia(1) } .brillo { filter: brightness(1.5) } .contraste { filter: contrast(1.5) } .grayscale { filter: grayscale(1) } .hue { filter: hue-rotate(150deg) } > Filtros CSS Codepen: RPMbbx
  32. #earth { width: 300px; height: 300px; border-radius: 50%; background: url(http://i.imgur.com/47xkq4v.jpg);

    background-repeat: repeat-x; margin: 5em auto; animation: rotacion 6s linear infinite; box-shadow: inset 0 0 25px 5px #000; } @keyframes rotacion { 0% { background-position: 620px } 100% { background-position: 0 } } > CSS es muy potente Codepen: OVQYEY
  33. > npm install -g clean-css > cleancss index.css --keep-line-breaks --rounding-precision

    1 --s0 --skip-shorthand-compacting --skip-advanced -o index.min.css > cat index.css | cleancss > Minificación CSS Respeta los saltos de línea (no une en una sola línea) Elimina comentarios CSS. Redondea unidades CSS a 1 decimales (def: 2) Desactiva optimizaciones (shorthands, compresión...)
  34. > LESS @import "core.less"; .transition(@time: 1s) { transition: all @time

    ease; -webkit-transition: all @time ease; } button.flat { border: 0; border-radius: 25px; padding: 10px; background: RGBA(0,0,0, 0.5); color: white; .transition(2s); &:hover { background: #A00; cursor: pointer; .transition; } } lesscss.org
  35. > autoprefixer img#mario { image-rendering: -webkit-optimize-contrast; image-rendering: -moz-crisp-edges; image-rendering: -o-pixelated;

    image-rendering: pixelated; } bit.ly/aprefixer img#mario { image-rendering: pixelated; } (ahora forma parte de postcss)
  36. > cssnext a:hover { color: color( red blackness(80%) ); //

    Oscurecer colores background-color: #44556677; // Soporta c. alfa en hex } :root { --mainColor: red; // Define variable CSS “mainColor” } a { color: var(--mainColor); // Usa variable CSS } img.sepia { filter: sepia(1); // Organiza código (autoprexifer, minify…) } cssnext.io
  37. > npm install -g uncss > uncss http://www.emezeta.com/ > out.css

    > CSS no utilizado Elimina estilos CSS sin utilizar. Guarda los cambios en el archivo out.css
  38. > SVG <svg xmlns="http://www.w3.org/2000/svg"> <path d="M9.43 206.88 l35-145 30.7 75.72

    30.73-72.86 25.7 139.28 42.15-135.7 42.87 137.85v -135L308 202.6V71.17h 102.14l-89.28 134.28 121.43-.7" /> </svg>
  39. > Optimización de SVG > npm install -g svgo >

    svgo -i manz.svg -p 2 --pretty -o manz.min. svg Done in 72 ms! 2.113 KiB - 88.3% = 0.247 KiB Redondea a 2 decimales las unidades utilizadas. Respeta los saltos de línea y usa indentaciones. 0,2KB
  40. > SVG path { fill: none; /* Trazos sin relleno

    */ stroke: #222; stroke-dasharray: 2000px 2000px; /* line,space */ stroke-dashoffset: 2000px; /* Desplazamiento */ stroke-width: 8px; } /* Al mover sobre la región SVG... */ svg:hover path { stroke-dashoffset: 0; transition: stroke-dashoffset 8s linear; }
  41. > JavaScript var nums = [1, 2, 3, 4, 5,

    6, 7, 8, 9, 10], fives = [] nums.forEach(v => { if (v % 5 === 0) fives.push(v) }) console.log(fives) lenguajejs.com
  42. > npm install -g uglifyjs > uglifyjs index.js --comments all

    --compress --lint -o index.min.js > cat index.min.js | uglifyjs --beautify 2>null > Minificación JS Preserva todos los comentarios JS (permite RegExp) Activa el compresor de código JS. Parsea y avisa de errores Javascript. Des-minifica el código Javascript mostrado con cat.
  43. > CoffeeScript var i, j; for (i = j =

    0; j <= 10; i = ++j) { alert(i); } coffeescript.org alert i for i in [0..10]
  44. > babel const PI = 3.14 let func = e

    => console.log(e) func(5) func(`El valor de PI es ${PI}.`) babeljs.io "use strict" var PI = 3.14 var func = function(e) { return console.log(e) } func(5) func("El valor de PI es " + PI + ".")
  45. > JQuery jquery.com var request = new XMLHttpRequest(); request.open('GET', '/url',

    true); request.onreadystatechange = function() { if (this.readyState === 4) if (this.status >= 200 && this.status < 400) var data = JSON.parse(this.responseText); }; request.send(); $.getJSON('/url', function(data) { // código });
  46. > XML w3.org/XML/ <?xml version="1.0" encoding="UTF-8" ?> <root> <array>1</array> <array>2</array>

    <array>3</array> <array>4</array> <array>5</array> <booleano>true</booleano> <objeto> <a>4</a> <b>Texto</b> <c /> </objeto> </root>
  47. > JSON json.org { "array": [1, 2, 3, 4, 5],

    "booleano": true, "objeto": { "a": 4, "b": "Texto", "c": null } } ejemplo.json 1 2 3 4 5 䘟 4 Texto Compatible con JS
  48. > YAML yaml.org --- array: [1, 2, 3, 4, 5]

    booleano: true objeto: a: 4 b: 'Texto' c: null
  49. jekyllrb.com --- layout: post category: tecnología tags: [web, blogs] ---

    # Título Esto es un **pequeño ejemplo** de un artículo escrito con *markdown* y *YAML Front Matter*. Nuevos CMS: Generadores estáticos
  50. sitioweb src index.jade menu.include.jade css index.less js index.js lazyload-plugin.js img

    logo.psd logo.png sitioweb dist index.html css index.css index.min.css js index.js index.min.js img logo.png src: Carpeta fuente dist: Carpeta destino
  51. > gulpfile.js gulpjs.com var gulp = require('gulp') var minifycss =

    require('gulp-minify-css') var autoprefixer = require('gulp-autoprefixer') var rename = require('gulp-rename') gulp.task('default', function() { return gulp.src('index.css') .pipe(autoprefixer()) .pipe(minifycss()) .pipe(rename('index.min.css')) .pipe(gulp.dest('dist/css')) }) Requiere instalar previamente: npm install -g gulp npm install --save-dev gulp gulp-minify-css gulp-autoprefixer gulp-rename > gulp
  52. > plugins gulpjs.com/plugins/ > gulp-minify-css > gulp-autoprefixer > gulp-concat >

    gulp-coffee > gulp-webserver > gulp-image > gulp-htmlmin > gulp-run > gulp-less > gulp-jade > gulp-babel > gulp-newer (con livereload) (jpg, png, svg...)