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

Más práticas de jQuery

joseli.to
November 30, 2013

Más práticas de jQuery

Palestra no Talk a Bit++

joseli.to

November 30, 2013
Tweet

More Decks by joseli.to

Other Decks in Programming

Transcript

  1. • Curso Ciência da Computação no CIn-UFPE • Co-fundador do

    Estudorama • Criador do Rabiscapp • Desenvolvedor no BlackBerry Tech Center Recife • BlackBerry Elite Member • Vencedor do NASA Space Apps Challenge Brazil 2013 • Vencedor do Startup Jam 2013 • Apaixonado pela web • Fã de Fórmula 1 e automobilismo S O B R E M I M
  2. • O que é jQuery • Histórico da web e

    do jQuery • Avanços do HTML5 • Quando você não precisa do jQuery • Como usar jQuery do jeito certo • Futuro da web A G E N D A
  3. Fonte: jQuery (http://jquery.com) jQuery is a fast, small, and feature-rich

    JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
  4. A V A N Ç O S • Padrões, padrões

    e mais padrões. • Mudanças semânticas • Plugin-free • Novas APIs nativas - Canvas - Aplicações offline - Mídia - Estrutura do DOM - Manipulação de eventos H T M L 5 D O
  5. Q U A N D O V O C Ê

    J Q U E R Y P R E C I S A N Ã O D O
  6. 1 Usar o jQuery apenas para selecionar elementos return new

    jQuery.fn.init( selector, context, rootjQuery ); if ( !selector ) { if ( selector.nodeType ) { if ( selector === "body" && !context && document.body ) { if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { match = quickExpr.exec( selector ); if ( match && (match[1] || !context) ) { if ( match[1] ) { elem = document.getElementById( match[2] ); if ( elem && elem.parentNode ) { if ( elem.id !== match[2] ) { this.length = 1; this[0] = elem; this.context = document; this.selector = selector; return this;
  7. 1 Usar o jQuery apenas para selecionar elementos O jQuery

    não retorna um elemento do DOM! $(‘#elemento’)
  8. 1 Usar o jQuery apenas para selecionar elementos O primeiro

    elemento do Objeto retornado pelo jQuery que é um elemento do DOM. $(‘#elemento’)[0]
  9. 3 Não manipule classes de um elemento com jQuery $(‘#elemento’).addClass(‘lindao’);

    $(‘#elemento’).addClass(‘lindao’); $(‘#elemento’).addClass(‘lindao’);
  10. 3 Não manipule classes de um elemento com jQuery $J(‘#elemento’).classList.add(‘lindao’);

    $J(‘#elemento’).classList.remove(‘lindao’); $J(‘#elemento’).classList.toggle(‘lindao’); $J(‘#elemento’).classList.contains(‘lindao’);
  11. 4 Não manipule atributos de um elemento com jQuery $('input').on('change',

    function () { var value = $(this).attr('value'); alert('O novo valor é:' + value); });
  12. 4 Não manipule atributos de um elemento com jQuery $('input').on('change',

    function () { alert('O novo valor é:' + input.value); });
  13. 4 Não manipule atributos de um elemento com jQuery $J('#elemento

    img').getAttribute('src'); $J('#elemento').id; $J('#elemento a').href; $J('#elemento img').setAttribute('src','fulano');
  14. 5 $('#elemento').on('mouseenter', function() { $(this).animate({ opacity: 0.5 }, 2000); }).on('mouseleave',

    function() { $(this).animate({ opacity: 1 }, 2000); }); Não use as efeitos do jQuery
  15. 5 Não use as efeitos do jQuery • el.hide(); •

    el.show(); • el.toggle(); • el.slideUp(); • el.slideDown(); • el.fadeIn(); • el.fadeOut(); • el.slideToggle(); • el.fadeToggle();
  16. 5 Não use as efeitos do jQuery • el.hide(); •

    el.show(); • el.toggle(); • el.slideUp(); • el.slideDown(); • el.fadeIn(); • el.fadeOut(); • el.slideToggle(); • el.fadeToggle();
  17. 5 #elemento { transition: opacity 2s linear; } #elemento:hover {

    opacity: 0; } Não use as efeitos do jQuery
  18. 5 Não use as efeitos do jQuery flash bounce shake

    tada swing wobble pulse flip flipInX flipOutX flipInY flipOutY fadeIn fadeInUp fadeInDown fadeInLeft fadeInRight fadeOut fadeOutUp fadeOutDown fadeOutLeft fadeOutRight fadeOutUpBig slideInDown slideInLeft slideInRight slideOutUp slideOutLeft slideOutRight fadeInUpBig fadeInDownBig fadeInLeftBig fadeInRightBig fadeOutDownBig fadeOutLeftBig fadeOutRightBig hinge rollIn rollOut
  19. 6 Use as APIs do browser $.ajaxSetup({ timeout: 1000, error:

    function(request, status, maybe_an_exception_object) { if(status != 'timeout') // Está online else // Está offline } }); Como verificar se o usuário está online?
  20. 6 Use as APIs do browser $.ajaxSetup({ timeout: 1000, error:

    function(request, status, maybe_an_exception_object) { if(status != 'timeout') // Está online else // Está offline } }); Como verificar se o usuário está online?
  21. 6 Use as APIs do browser if (navigator.onLine) { //

    Está online } Como verificar se o usuário está online?
  22. 6 Use as APIs do browser • onLine • language

    • platform • userAgent • battery, vibrate, geolocation...
  23. 8 Evite ao máximo injetar código no carregamento com jQuery

    $(“body”).html($(“body”).html()+ “<h1>Talk a bit++</h1>”); $(“body”).append(“<h1>Talk a bit++</h1>”);
  24. 8 Evite ao máximo injetar código no carregamento com jQuery

    $J(“#elemento”).innerHTML $J(“#elemento”).innerHTML = “Talk a bit”; $J(“#elemento”).innerHTML += “Talk a bit++”;
  25. 8 Evite ao máximo injetar código no carregamento com jQuery

    var myDiv = document.createElement('div'); myDiv.id = “elemento”; myDiv.setAttribute(“class”,”lindao”); body.append(myDiv);
  26. 1 0 Armazenar Data com jQuery var html = [];

    for (var key in el.dataset) { html.push(key, ': ', el.dataset[key], '<br>'); } el.innerHTML = html.join('');
  27. C O M O U S A R J Q

    U E R Y J E I T O D O C E R T O
  28. 2 AJAX function sendRequest(url,callback,postData) { var req = createXMLHTTPObject(); if

    (!req) return; var method = (postData) ? "POST" : "GET"; req.open(method,url,true); req.setRequestHeader('User-Agent','XMLHTTP/1.0'); if (postData) req.setRequestHeader('Content-type','application/x-www-form- urlencoded'); req.onreadystatechange = function () { if (req.readyState != 4) return; if (req.status != 200 && req.status != 304) { return; } callback(req); } if (req.readyState == 4) return; req.send(postData); } var XMLHttpFactories = [ function () {return new XMLHttpRequest()}, function () {return new ActiveXObject("Msxml2.XMLHTTP")}, function () {return new ActiveXObject("Msxml3.XMLHTTP")}, function () {return new ActiveXObject("Microsoft.XMLHTTP")} ]; function createXMLHTTPObject() { var xmlhttp = false; for (var i=0;i<XMLHttpFactories.length;i++) { try { xmlhttp = XMLHttpFactories[i](); } catch (e) { continue; } break; } return xmlhttp; }
  29. 2 AJAX function sendRequest(url,callback,postData) { var req = createXMLHTTPObject(); if

    (!req) return; var method = (postData) ? "POST" : "GET"; req.open(method,url,true); req.setRequestHeader('User-Agent','XMLHTTP/1.0'); if (postData) req.setRequestHeader('Content-type','application/x-www-form- urlencoded'); req.onreadystatechange = function () { if (req.readyState != 4) return; if (req.status != 200 && req.status != 304) { return; } callback(req); } if (req.readyState == 4) return; req.send(postData); } var XMLHttpFactories = [ function () {return new XMLHttpRequest()}, function () {return new ActiveXObject("Msxml2.XMLHTTP")}, function () {return new ActiveXObject("Msxml3.XMLHTTP")}, function () {return new ActiveXObject("Microsoft.XMLHTTP")} ]; function createXMLHTTPObject() { var xmlhttp = false; for (var i=0;i<XMLHttpFactories.length;i++) { try { xmlhttp = XMLHttpFactories[i](); } catch (e) { continue; } break; } return xmlhttp; }
  30. 2 AJAX $.ajax({ type: "GET", url: "ocean.php", data: { name:

    "Sponge", last: "Bob" } }).done(function( msg ) { alert(msg); });
  31. 3 Adicionar e modificar elementos diretamente no DOM • el.text()

    • el.html() • el.append() • el.css()
  32. 5 Aproveite-se dos utilitários • $.find() • $.map() • $.grep()

    • $.inArray() • $.merge() • $.extend()
  33. 6 Seletores especiais do jQuery • el:has() • el:contains() •

    el:not() • el:filter() • el:animated • el:hidden • el:visible
  34. 8 Faça Cache e Chaining function setDiv() { $("#elemento").attr("title", $("input").text());

    $("#elemento").css("color", "white"); $("#elemento").css("background-color", "purple"); $("#elemento").fadeIn(); }
  35. 8 Faça Cache e Chaining function setDivMelhor() { var el

    = $("#elemento"); el.attr("title", $("input").text()); el.css("color", "white"); el.css("background-color", "purple"); el.fadeIn(); }
  36. 8 Faça Cache e Chaining function setDivBemMelhor() { var el

    = $("#elemento"); el.attr("title", $("input").text()).css("color", "white").css("background-color", "purple").fadeIn(); }
  37. 9 Ok, o el.animate() ainda é seu amigo $('#evento').on("click",function(){ $('html,

    body').animate({scrollTop:0}, 700); }); $('#learnmenu').on("click",function(){ $('html, body').animate({scrollTop:$ ("#learn").offset().top - 110 }, 700); });
  38. 1 0 Já que você pode, abuse dos callbacks! $("#elemento").css({'top':

    300, 'left':200}, function(){ // Meu callback });
  39. 1 4 Use só o jQuery que de fato você

    precisa http://projects.jga.me/jquery-builder/
  40. <canvas id="blue-box-land"></canvas> var win = $(window); var canvas = $("#blue-box-land");

    function resize() { canvas .width(win.width()) .height(win.height()); } win.resize(resize).resize(); var ctx = canvas[0].getContext('2d'); ctx.fillStyle = "blue"; ctx.fillRect(50, 50, 200, 50);
  41. var div = document.createElement("div"); div.style.width = "50%"; div.style.height = "50%";

    div.style.position = "relative"; div.style.top = "50%"; div.style.left = "50%"; div.style.marginLeft = "-25%"; div.style.marginTop = "-8%"; div.style.backgroundColor = "blue"; var body = document.getElementsByTagName("body")[0]; body.appendChild(div);
  42. $.fn.BlueBox = function() { this.css({ backgroundColor: 'blue', position: 'absolute', height:

    '60%', width: '60%', left: '20%', top: '20%' }); }; $( '.box' ).BlueBox(); <div class="box"></div>
  43. Joselito Júnior BlackBerry Elite @joselitojunior1 www.joselitojunior.com O B R I

    G A D O blackberrydeveloper.com.br jfnj.tk/jquery-tab