folder names

This commit is contained in:
Jen Looper
2020-11-09 22:51:04 -05:00
parent 33e5d5f777
commit 1d81829ac1
367 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
*Complete this quiz by checking one answer per question.*
1. To get a better view of your site's performance, clear its cache and reload in the profiler
- [ ] true
- [ ] false
2. Browser extensions are inherently performant
- [ ] true
- [ ] false
3. Analyze the following for performance bottlenecks
- [ ] DOM traversals
- [ ] JavaScript optimizations
- [ ] Asset management
- [ ] All the above

View File

@@ -0,0 +1,18 @@
*Complete this quiz in class.*
1. Test the performance of your app
- [ ] Using the browser's tools
- [ ] Using a separate software package
- [ ] Manually
2. The 'performance' of a web site is an analysis of
- [ ] How fast it loads
- [ ] How fast the code on it runs
- [ ] Both of the above
3. Overall, the 'weight' of web pages over the past few years has gotten
- [ ] lighter
- [ ] heavier
- [ ] stayed the same

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 WebDev-For-Beginners
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,157 @@
# Browser Extension Project Part 3: Learn about Background Tasks and Performance
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
### Introduction:
In the last two lessons of this module, you learned how to build a form and display area for data fetched from an API. It's a very standard way of creating web presences on the web. You even learned how to handle fetching data asyncronously. Your browser extension is very nearly complete.
It remains to manage some background tasks, including refreshing the color of the extension's icon, so this is a great time to talk about how the browser manages this kind of task. Let's think about these browser tasks in the context of the performance of your web assets as you build them.
## Web Performance Basics
> "Website performance is about two things: how fast the page loads, and how fast the code on it runs." -- [Zack Grossbart](https://www.smashingmagazine.com/2012/06/javascript-profiling-chrome-developer-tools/)
The topic of how to make your web sites blazingly fast on all kinds of devices, for all kinds of users, in all kinds of situations, is unsurprisingly vast. Here are some points to keep in mind as you build either a standard web project or a browser extension.
The first thing you need to do to ensure that your site is running efficiently is to gather data about its performance. The first place to do this is in the developer tools of your web browser. In Edge, you can select the three dots on the top right of the browser, then navigate to More Tools > Developer Tools and open the Performance tab.
The Performance tab contains a Profiling tool. Open a web site (try, for example, https://www.microsoft.com) and click the 'Record' button, then refresh the site. Stop the recording at any time, and you will be able to see the routines that are generated to 'script', 'render', and 'paint' the site:
![Edge profiler](./images/profiler.png)
✅ Visit the [Microsoft Documentation](https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide/performance) on the Performance panel in Edge
> Tip: to get a true reading of your web site's startup time, clear your browser's cache
Select elements of the profile timeline to zoom in on events that happen while your page loads.
Get a snapshot of your page's performance by selecting a part of the profile timeline and looking at the summary pane:
![Edge profiler snapshot](./images/snapshot.png)
Check the Event Log pane to see if any event took longer than 15 ms:
![Edge event log](./images/log.png)
✅ Get to know your profiler! Open the developer tools on this site and see if there are any bottlenecks. What's the slowest-loading asset? The fastest?
## Profiling checks
In general there are some "problem areas" that every web developer should watch for when building a site, so as to avoid nasty surprises when it's time to deploy to production.
**Asset sizes**: The web has gotten 'heavier', and thus slower, over the past few years. Some of this weight has to do with the use of images.
✅ Look through the [Internet Archive](https://httparchive.org/reports/page-weight) for a historical view of page weight and more.
A good practice is to ensure that your images are optimized, delivered at the right size and resolution for your users.
**DOM traversals**: The browser has to build its Document Object Model based on the code you write, so it's in the interest of good page performance to keep your tags minimal, only using and styling what the page needs. To this point, excess CSS associated with a page could be optimized; styles that need to be used only on one page don't need to be included in the main style sheet, for example.
**JavaScript**: Every JavaScript developer should watch for 'render-blocking' scripts that must be loaded before the rest of the DOM can be traversed and painted to the browser. Consider using `defer` with your inline scripts (as is done in the Terrarium module).
✅ Try some sites on a [Site Speed Test website](https://www.webpagetest.org/) to learn more about the common checks that are done to determine site performance.
Now that you have an idea on how the browser renders the assets you send to it, let's look at the last few things you need to do to complete your extension:
### Create a function to calculate color
Working in `/src/index.js`, add a function called `calculateColor()` after the series of `const` variables you set to gain access to the DOM:
```JavaScript
function calculateColor(value) {
let co2Scale = [0, 150, 600, 750, 800];
let colors = ['#2AA364', '#F5EB4D', '#9E4229', '#381D02', '#381D02'];
let closestNum = co2Scale.sort((a, b) => {
return Math.abs(a - value) - Math.abs(b - value);
})[0];
console.log(value + ' is closest to ' + closestNum);
let num = (element) => element > closestNum;
let scaleIndex = co2Scale.findIndex(num);
let closestColor = colors[scaleIndex];
console.log(scaleIndex, closestColor);
chrome.runtime.sendMessage({ action: 'updateIcon', value: { color: closestColor } });
}
```
What's going on here? You pass in a value (the carbon intensity) from the API call you completed in the last lesson, and then you calculate how close its value is to the index presented in colors array. Then you send that closest color value over to the chrome runtime.
The chrome.runtime has [an API](https://developer.chrome.com/extensions/runtime) that handles all kinds of background tasks, and your extension is leveraging that:
> "Use the chrome.runtime API to retrieve the background page, return details about the manifest, and listen for and respond to events in the app or extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs."
✅ If you're developing this browser extension for Edge, it might surprise you that you're using a chrome API. The newer Edge browser versions run on the Chromium browser engine, so you can leverage these tools.
> Note, if you want to profile a browser extension, launch the dev tools from within the extension itself, as it is its own separate browser instance.
### Set a default icon color
Now, in the `init()` function, set the icon to be generic green to start by again calling chrome's `updateIcon` action:
```JavaScript
chrome.runtime.sendMessage({
action: 'updateIcon',
value: {
color: 'green',
},
});
```
### Call the function, execute the call
Next, call that function you just created by adding it to the promise returned by the C02Signal API:
```JavaScript
//let CO2...
calculateColor(CO2);
```
And finally, in `/dist/background.js`, add the listener for these background action calls:
```JavaScript
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === 'updateIcon') {
chrome.browserAction.setIcon({ imageData: drawIcon(msg.value) });
}
});
//borrowed from energy lollipop extension, nice feature!
function drawIcon(value) {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
context.beginPath();
context.fillStyle = value.color;
context.arc(100, 100, 50, 0, 2 * Math.PI);
context.fill();
return context.getImageData(50, 50, 100, 100);
}
```
In this code, you are adding a listener for any messages coming to the backend task manager. If it's called 'updateIcon', then the next code is run, to draw an icon of the proper color using the Canvas API.
✅ You'll learn more about the Canvas API in the [Space Game lessons](../../space-game/drawing-to-canvas/README.md).
Now, rebuild your extension (`npm run build`), refresh and launch your extension, and watch the color change. Is it a good time to run an errand or wash the dishes? Now you know!
Congratulations, you've built a useful browser extension and learned more about how the browser works and how to profile its performance.
---
## 🚀 Challenge
Investigate some open source web sites have been around a long time ago, and, based on their GitHub history, see if you can determine how they were optimized over the years for performance, if at all. What is the most common pain point?
## [Post-lecture quiz](.github/post-lecture-quiz.md)
## Review & Self Study
Consider signing up for a [performance newsletter](https://perf.email/)
Investigate some of the ways that browsers gauge web performance by looking through the performance tabs in their web tools. Do you find any major differences?
## Assignment
[Analyze a site for performance](assignment.md)

View File

@@ -0,0 +1,9 @@
# Analyze a site for performance
Provide a detailed report of a web site, showing areas where performance is problematic. Analyze why the site is slow and what you could do to speed it up. Don't rely only on the browser tools, but do some research on other tools that can help your report
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | ---------------------------------------------------------------------------------------------------------- | --------------------------- | ----------------------------- |
| | A report is presented with details drawn not only from browser tools but from 3rd party tools if available | A basic report is presented | A minimal report is presented |

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 830 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

View File

@@ -0,0 +1,153 @@
# Proyecto de extensión del navegador, parte 3: Más información sobre el rendimiento y las tareas en segundo plano
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
### Introducción:
En las dos últimas lecciones de este módulo, aprendió cómo crear un formulario y un área de visualización para los datos obtenidos de una API. Es una forma muy estándar de crear presencias web en la web. Incluso aprendió a manejar la obtención de datos de forma asincrónica. La extensión de su navegador está casi completa.
Queda por administrar algunas tareas en segundo plano, incluida la actualización del color del icono de la extensión, por lo que este es un buen momento para hablar sobre cómo el navegador administra este tipo de tareas. Pensemos en estas tareas del navegador en el contexto del rendimiento de sus activos web a medida que los crea.
## Conceptos básicos sobre el rendimiento web
> "El rendimiento del sitio web se trata de dos cosas: qué tan rápido se carga la página y qué tan rápido se ejecuta el código". - [Zack Grossbart](https://www.smashingmagazine.com/2012/06/javascript-profiling-chrome-developer-tools/)
El tema de cómo hacer que sus sitios web sean increíblemente rápidos en todo tipo de dispositivos, para todo tipo de usuarios, en todo tipo de situaciones, es sorprendentemente vasto. Estos son algunos puntos que debe tener en cuenta al crear un proyecto web estándar o una extensión de navegador.
Lo primero que debe hacer para asegurarse de que su sitio funcione de manera eficiente es recopilar datos sobre su rendimiento. El lugar para hacer esto es en las herramientas de desarrollo de su navegador web. En Edge, puede seleccionar los tres puntos en la parte superior derecha del navegador, luego navegar a Más herramientas> Herramientas de desarrollo y abrir la pestaña Rendimiento.
La pestaña Rendimiento contiene una herramienta de creación de perfiles. Abra un sitio web (pruebe, por ejemplo, https://www.microsoft.com) y haga clic en el botón 'Grabar', luego actualice el sitio. Detenga la grabación en cualquier momento y podrá ver las rutinas que se generan para 'escribir', 'renderizar' y 'pintar' el sitio:
![Edge profiler](./images/profiler.png)
✅ Visite la [Documentación de Microsoft](https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide/performance) en el panel Rendimiento en Edge
> Consejo: para obtener una lectura real de la hora de inicio de su sitio web, borre la memoria caché de su navegador
Seleccione elementos de la línea de tiempo del perfil para ampliar los eventos que suceden mientras se carga su página.
Obtenga una instantánea del rendimiento de su página seleccionando una parte de la línea de tiempo del perfil y mirando el panel de resumen:
![Instantánea de Edge Profiler](./images/snapshot.png)
Compruebe el panel Registro de eventos para ver si algún evento tardó más de 15 ms:
![Registro de eventos de Edge](./images/log.png)
✅ ¡Conoce a tu perfilador! Abra las herramientas de desarrollo en este sitio y vea si hay cuellos de botella. ¿Cuál es el activo de carga más lenta? ¿El más rápido?
## Comprobaciones de perfiles
En general, hay algunas "áreas problemáticas" que todo desarrollador web debe tener en cuenta al crear un sitio, para evitar sorpresas desagradables cuando llegue el momento de implementarlo en producción.
**Tamaños de activos**: la Web se ha vuelto 'más pesada' y, por lo tanto, más lenta en los últimos años. Parte de este peso tiene que ver con el uso de imágenes.
✅ Busque en el [Archivo de Internet](https://httparchive.org/reports/page-weight) una vista histórica del peso de la página y más.
Una buena práctica es asegurarse de que sus imágenes estén optimizadas, entregadas con el tamaño y la resolución adecuados para sus usuarios.
**Recorridos de DOM**: el navegador tiene que construir su Modelo de Objetos de Documento basado en el código que usted escribe, por lo que es de interés para un buen rendimiento de la página mantener sus etiquetas al mínimo, solo usando y estilizando lo que la página necesita. Hasta este punto, se podría optimizar el exceso de CSS asociado con una página; los estilos que deben usarse solo en una página no necesitan incluirse en la hoja de estilo principal, por ejemplo.
**JavaScript**: Todo desarrollador de JavaScript debe estar atento a los scripts de 'bloqueo de renderizado' que deben cargarse antes de que el resto del DOM pueda atravesarse y pintarse en el navegador. Considere usar "diferir" con sus scripts en línea (como se hace en el módulo Terrarium).
✅ Pruebe algunos sitios en un [sitio web de prueba de velocidad del sitio](https://www.webpagetest.org/) para obtener más información sobre las comprobaciones comunes que se realizan para determinar el rendimiento del sitio.
Ahora que tiene una idea de cómo el navegador representa los recursos que le envía, veamos las últimas cosas que debe hacer para completar su extensión:
### Crea una función para calcular el color
Trabajando en `/ src / index.js`, agregue una función llamada` calculateColor () `después de la serie de variables` const` que estableció para obtener acceso al DOM:
```JavaScript
function calculateColor(value) {
let co2Scale = [0, 150, 600, 750, 800];
let colors = ['#2AA364', '#F5EB4D', '#9E4229', '#381D02', '#381D02'];
let closestNum = co2Scale.sort((a, b) => {
return Math.abs(a - value) - Math.abs(b - value);
})[0];
console.log(value + ' is closest to ' + closestNum);
let num = (element) => element > closestNum;
let scaleIndex = co2Scale.findIndex(num);
let closestColor = colors[scaleIndex];
console.log(scaleIndex, closestColor);
chrome.runtime.sendMessage({ action: 'updateIcon', value: { color: closestColor } });
}
```
¿Que está pasando aqui? Pasa un valor (la intensidad de carbono) de la llamada API que completó en la última lección, y luego calcula qué tan cerca está su valor del índice presentado en la matriz de colores. Luego, envía el valor de color más cercano al tiempo de ejecución de Chrome.
Chrome.runtime tiene [una API](https://developer.chrome.com/extensions/runtime) que maneja todo tipo de tareas en segundo plano, y tu extensión aprovecha eso:
> "Utilice la API chrome.runtime para recuperar la página de fondo, devolver detalles sobre el manifiesto y escuchar y responder a eventos en el ciclo de vida de la aplicación o extensión. También puede utilizar esta API para convertir la ruta relativa de las URL a URL calificadas".
✅ Si está desarrollando esta extensión de navegador para Edge, puede que le sorprenda que esté utilizando una API de Chrome. Las versiones más recientes del navegador Edge se ejecutan en el motor del navegador Chromium, por lo que puede aprovechar estas herramientas.
> Tenga en cuenta que si desea crear un perfil de una extensión de navegador, inicie las herramientas de desarrollo desde la propia extensión, ya que es su propia instancia de navegador independiente.
### Establecer un color de icono predeterminado
Ahora, en la función `init ()`, configure el ícono en verde genérico para comenzar nuevamente llamando a la acción `updateIcon` de Chrome:
```JavaScript
chrome.runtime.sendMessage({
action: 'updateIcon',
value: {
color: 'green',
},
});
```
### Llame a la función, ejecute la llamada
A continuación, llame a la función que acaba de crear agregándola a la promesa devuelta por la API C02Signal:
```JavaScript
//let CO2...
calculateColor(CO2);
```
Y finalmente, en `/dist/background.js`, agregue el oyente para estas llamadas de acción en segundo plano:
```JavaScript
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === 'updateIcon') {
chrome.browserAction.setIcon({ imageData: drawIcon(msg.value) });
}
});
//tomado de la extensión Energy Lollipop, ¡buena característica!
function drawIcon(value) {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
context.beginPath();
context.fillStyle = value.color;
context.arc(100, 100, 50, 0, 2 * Math.PI);
context.fill();
return context.getImageData(50, 50, 100, 100);
}
```
En este código, está agregando un oyente para cualquier mensaje que llegue al administrador de tareas de backend. Si se llama 'updateIcon', entonces se ejecuta el siguiente código para dibujar un icono del color adecuado usando la API de Canvas.
✅ Aprenderá más sobre la API Canvas en las [lecciones del juego espacial](../../space-game/drawing-to-canvas/README.md).
Ahora, reconstruya su extensión (`npm run build`), actualice y ejecute su extensión, y observe el cambio de color. ¿Es un buen momento para hacer un mandado o lavar los platos? ¡Ahora lo sabes!
Felicitaciones, ha creado una extensión de navegador útil y ha aprendido más sobre cómo funciona el navegador y cómo perfilar su rendimiento.
🚀 Desafío: Investigue algunos sitios web de código abierto que han existido hace mucho tiempo y, según su historial de GitHub, vea si puede determinar cómo se optimizaron a lo largo de los años para el rendimiento, si es que lo hicieron. ¿Cuál es el punto de dolor más común?
## [Post-lecture prueba] (.github/post-lecture-quiz.md)
## Revisión y autoestudio
Considere suscribirse a un [boletín informativo de rendimiento](https://perf.email/)
Investigue algunas de las formas en que los navegadores miden el rendimiento web consultando las pestañas de rendimiento de sus herramientas web. ¿Encuentra diferencias importantes?
**Tarea**: [Analizar el rendimiento de un sitio](assignment.md)

View File

@@ -0,0 +1,9 @@
# Analizar el rendimiento de un sitio
Proporcione un informe detallado de un sitio web, que muestre las áreas donde el rendimiento es problemático. Analice por qué el sitio es lento y qué podría hacer para acelerarlo. No confíe solo en las herramientas del navegador, investigue un poco sobre otras herramientas que pueden ayudar a su informe
## Rúbrica
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
| -------- | -------------------------------------------------- -------------------------------------------------- ------ | --------------------------- | ----------------------------- |
| | Se presenta un informe con detalles extraídos no solo de las herramientas del navegador, sino también de herramientas de terceros, si están disponibles | Se presenta un informe básico | Se presenta un informe mínimo |