|
1 | | -# Browser environment, specs |
| 1 | +# Entorno del navegador, especificaciones |
2 | 2 |
|
3 | | -The JavaScript language was initially created for web browsers. Since then, it has evolved and become a language with many uses and platforms. |
| 3 | +El lenguaje JavaScript fue creado inicialmente para los navegadores web. Desde entonces, ha evolucionado y se ha convertido en un lenguaje con muchos usos y plataformas. |
4 | 4 |
|
5 | | -A platform may be a browser, or a web-server, or a washing machine, or another *host*. Each of them provides platform-specific functionality. The JavaScript specification calls that a *host environment*. |
| 5 | +Una plataforma puede ser un navegador, un servidor web, una lavadora u otro *host*. Cada uno de ellos proporciona una funcionalidad específica. La especificación de JavaScript lo llama *entorno host*. |
6 | 6 |
|
7 | | -A host environment provides platform-specific objects and functions additional to the language core. Web browsers give a means to control web pages. Node.JS provides server-side features, and so on. |
| 7 | +Un entorno host proporciona objetos específicos de la plataforma y funciones adicionales al núcleo del lenguaje. Los navegadores web proporcionan un medio para controlar las páginas web. Node.JS proporciona características del lado del servidor, y así sucesivamente. |
8 | 8 |
|
9 | | -Here's a bird's-eye view of what we have when JavaScript runs in a web-browser: |
| 9 | +Aquí tienes una vista general de lo que tenemos cuando JavaScript se ejecuta en un navegador web: |
10 | 10 |
|
11 | 11 |  |
12 | 12 |
|
13 | | -There's a "root" object called `window`. It has two roles: |
| 13 | +Hay un objeto "raíz" llamado `window`.Tiene dos roles: |
14 | 14 |
|
15 | | -1. First, it is a global object for JavaScript code, as described in the chapter <info:global-object>. |
16 | | -2. Second, it represents the "browser window" and provides methods to control it. |
| 15 | +1. Primero, es un objeto global para el código JavaScript, como se describe en el capítulo [Objeto global](/global-object). |
| 16 | +2. En segundo lugar, representa la "ventana del navegador" y proporciona métodos para controlarla. |
17 | 17 |
|
18 | | -For instance, here we use it as a global object: |
| 18 | +Por ejemplo, aquí lo usamos como un objeto global: |
19 | 19 |
|
20 | 20 | ```js run |
21 | 21 | function sayHi() { |
22 | 22 | alert("Hello"); |
23 | 23 | } |
24 | 24 |
|
25 | | -// global functions are accessible as properties of window |
| 25 | +// Las funciones globales son accesibles como propiedades de window |
26 | 26 | window.sayHi(); |
27 | 27 | ``` |
28 | 28 |
|
29 | | -And here we use it as a browser window, to see the window height: |
| 29 | +Y aquí lo usamos como una ventana del navegador, para ver la altura de la ventana: |
30 | 30 |
|
31 | 31 | ```js run |
32 | | -alert(window.innerHeight); // inner window height |
| 32 | +alert(window.innerHeight); // altura interior de la ventana |
33 | 33 | ``` |
34 | 34 |
|
35 | | -There are more window-specific methods and properties, we'll cover them later. |
| 35 | +Hay más métodos y propiedades específicos de `window`, los cubriremos más adelante. |
36 | 36 |
|
37 | | -## Document Object Model (DOM) |
| 37 | +## Modelo de Objetos del Documento (DOM) |
38 | 38 |
|
39 | | -The `document` object gives access to the page content. We can change or create anything on the page using it. |
| 39 | +El objeto de `document` da acceso al contenido de la página. Con él podemos cambiar o crear cualquier cosa en la página. |
40 | 40 |
|
41 | | -For instance: |
| 41 | +Por ejemplo: |
42 | 42 | ```js run |
43 | | -// change the background color to red |
| 43 | +// cambia el color de fondo a rojo |
44 | 44 | document.body.style.background = "red"; |
45 | 45 |
|
46 | | -// change it back after 1 second |
| 46 | +// deshace el cambio después de 1 segundo |
47 | 47 | setTimeout(() => document.body.style.background = "", 1000); |
48 | 48 | ``` |
49 | 49 |
|
50 | | -Here we used `document.body.style`, but there's much, much more. Properties and methods are described in the specification. There happen to be two working groups who develop it: |
| 50 | +Aquí usamos `document.body.style`, pero hay muchos, muchos más. Las propiedades y métodos se describen en la especificación. Sucede que hay dos grupos de trabajo que lo desarrollan: |
51 | 51 |
|
52 | | -1. [W3C](https://en.wikipedia.org/wiki/World_Wide_Web_Consortium) -- the documentation is at <https://www.w3.org/TR/dom>. |
53 | | -2. [WhatWG](https://en.wikipedia.org/wiki/WHATWG), publishing at <https://dom.spec.whatwg.org>. |
| 52 | +1. [W3C](https://es.wikipedia.org/wiki/World_Wide_Web_Consortium) -- la documentación se encuentra en <https://www.w3.org/TR/dom>. |
| 53 | +2. [WhatWG](https://es.wikipedia.org/wiki/Web_Hypertext_Application_Technology_Working_Group), publicado en <https://dom.spec.whatwg.org>. |
54 | 54 |
|
55 | | -As it happens, the two groups don't always agree, so it's like we have two sets of standards. But they are very similar and eventually things merge. The documentation that you can find on the given resources is very similar, with about a 99% match. There are very minor differences that you probably won't notice. |
| 55 | +Como es de esperar, los dos grupos no siempre están de acuerdo, así que es como si tuviéramos dos conjuntos de estándares. Pero son muy similares y eventualmente las cosas se fusionan. La documentación que puede encontrar en los recursos dados es muy similar, con aproximadamente un 99% de coincidencia. Hay diferencias muy pequeñas que probablemente no notarás. |
56 | 56 |
|
57 | | -Personally, I find <https://dom.spec.whatwg.org> more pleasant to use. |
| 57 | +Personalmente, encuentro <https://dom.spec.whatwg.org> más agradable de usar. |
58 | 58 |
|
59 | | -In the ancient past, there was no standard at all -- each browser implemented however it wanted. Different browsers had different sets, methods, and properties for the same thing, and developers had to write different code for each of them. Dark, messy times. |
| 59 | +En el pasado lejano, no existía ninguna norma en absoluto: cada navegador se implementaba como quería. Diferentes navegadores tenían diferentes métodos y propiedades para la misma cosa, y los desarrolladores tenían que escribir un código diferente para cada uno de ellos. Tiempos oscuros, desordenados. |
60 | 60 |
|
61 | | -Even now we can sometimes meet old code that uses browser-specific properties and works around incompatibilities. But, in this tutorial we'll use modern stuff: there's no need to learn old things until you really need to (chances are high that you won't). |
| 61 | +Incluso ahora, podemos encontrarnos con código antiguo que usa propiedades específicas del navegador y soluciona las incompatibilidades. Pero, en este tutorial usaremos cosas modernas: no hay necesidad de aprender cosas antiguas hasta que realmente lo necesites (es muy probable que no lo hagas). |
62 | 62 |
|
63 | | -Then the DOM standard appeared, in an attempt to bring everyone to an agreement. The first version was "DOM Level 1", then it was extended by DOM Level 2, then DOM Level 3, and now it's reached DOM Level 4. People from WhatWG group got tired of version numbers and are calling it just "DOM", without a number. So we'll do the same. |
| 63 | +Luego apareció el estándar DOM, en un intento de llevar a todos a un acuerdo. La primera versión fue "DOM Level 1", luego fue extendida por DOM Level 2, luego DOM Level 3, y ahora llegó a DOM Level 4. La gente del grupo WhatWG se cansó de los números de versión y lo están llamando simplemente "DOM", sin un numero. Así que haremos lo mismo. |
64 | 64 |
|
65 | | -```smart header="DOM is not only for browsers" |
66 | | -The DOM specification explains the structure of a document and provides objects to manipulate it. There are non-browser instruments that use it too. |
| 65 | +```smart header="DOM no es solo para navegadores" |
| 66 | +La especificación DOM explica la estructura de un documento y proporciona objetos para manipularlo. Hay instrumentos que no son del navegador que también lo utilizan. |
67 | 67 |
|
68 | | -For instance, server-side tools that download HTML pages and process them use the DOM. They may support only a part of the specification though. |
| 68 | +Por ejemplo, las herramientas del lado del servidor que descargan páginas HTML y las procesan utilizan el DOM. Sin embargo, pueden soportar solo una parte de la especificación. |
69 | 69 | ``` |
70 | 70 |
|
71 | | -```smart header="CSSOM for styling" |
72 | | -CSS rules and stylesheets are not structured like HTML. There's a separate specification [CSSOM](https://www.w3.org/TR/cssom-1/) that explains how they are represented as objects, and how to read and write them. |
| 71 | +```smart header="CSSOM para los estilos" |
| 72 | +Las reglas CSS y las hojas de estilo no están estructuradas como HTML. Hay una especificación [CSSOM](https://www.w3.org/TR/cssom-1/) separada, que explica cómo se representan como objetos, y cómo leerlos y escribirlos. |
73 | 73 |
|
74 | | -CSSOM is used together with DOM when we modify style rules for the document. In practice though, CSSOM is rarely required, because usually CSS rules are static. We rarely need to add/remove CSS rules from JavaScript, so we won't cover it right now. |
| 74 | +CSSOM se usa junto con DOM cuando modificamos las reglas de estilo para el documento. En la práctica, sin embargo, rara vez se requiere CSSOM, porque generalmente las reglas de CSS son estáticas. Rara vez necesitamos agregar/eliminar reglas CSS desde JavaScript, por lo que no lo cubriremos ahora. |
75 | 75 | ``` |
76 | 76 |
|
77 | | -## BOM (part of HTML spec) |
| 77 | +## BOM (parte de la especificación HTML) |
78 | 78 |
|
79 | | -Browser Object Model (BOM) are additional objects provided by the browser (host environment) to work with everything except the document. |
| 79 | +El Modelo de Objetos del Navegador (BOM) son objetos adicionales proporcionados por el navegador (entorno host) para trabajar con todo excepto el documento. |
80 | 80 |
|
81 | | -For instance: |
| 81 | +Por ejemplo: |
82 | 82 |
|
83 | | -- The [navigator](mdn:api/Window/navigator) object provides background information about the browser and the operating system. There are many properties, but the two most widely known are: `navigator.userAgent` -- about the current browser, and `navigator.platform` -- about the platform (can help to differ between Windows/Linux/Mac etc). |
84 | | -- The [location](mdn:api/Window/location) object allows us to read the current URL and can redirect the browser to a new one. |
| 83 | +- El objeto [navigator](mdn:api/Window/navigator), proporciona información sobre el navegador y el sistema operativo. Hay muchas propiedades, pero las dos más conocidas son: `navigator.userAgent` -- sobre el navegador actual, y `navigator.platform` -- sobre la plataforma (puede ayudar a diferenciar entre Windows/Linux/Mac, etc.). |
85 | 84 |
|
86 | | -Here's how we can use the `location` object: |
| 85 | +El objeto [location](mdn:api/Window/location), nos permite leer la URL actual y puede redirigir el navegador a uno nuevo. |
| 86 | + |
| 87 | +Aquí vemos cómo podemos usar el objeto `location`: |
87 | 88 |
|
88 | 89 | ```js run |
89 | | -alert(location.href); // shows current URL |
| 90 | +alert(location.href); // muestra la URL actual |
90 | 91 | if (confirm("Go to wikipedia?")) { |
91 | | - location.href = "https://wikipedia.org"; // redirect the browser to another URL |
| 92 | + location.href = "https://wikipedia.org"; // redirigir el navegador a otra URL |
92 | 93 | } |
93 | 94 | ``` |
94 | 95 |
|
95 | | -Functions `alert/confirm/prompt` are also a part of BOM: they are directly not related to the document, but represent pure browser methods of communicating with the user. |
96 | | - |
| 96 | +Las funciones `alert/confirm/prompt` también forman parte de BOM: no están directamente relacionadas con el documento, sino que representan métodos de comunicación puros con el usuario. |
97 | 97 |
|
98 | | -```smart header="HTML specification" |
99 | | -BOM is the part of the general [HTML specification](https://html.spec.whatwg.org). |
| 98 | +```smart header="Especificación de HTML" |
| 99 | +BOM es la parte general de la especificación de HTML. |
100 | 100 |
|
101 | | -Yes, you heard that right. The HTML spec at <https://html.spec.whatwg.org> is not only about the "HTML language" (tags, attributes), but also covers a bunch of objects, methods and browser-specific DOM extensions. That's "HTML in broad terms". |
| 101 | +Sí, oíste bien. La especificación HTML en <https://html.spec.whatwg.org> no solo trata sobre el "lenguaje HTML" (etiquetas, atributos), sino que también cubre un montón de objetos, métodos y extensiones DOM específicas del navegador. Eso es "HTML en términos generales". |
102 | 102 | ``` |
103 | 103 |
|
104 | | -## Summary |
| 104 | +## Resumen |
105 | 105 |
|
106 | | -Talking about standards, we have: |
| 106 | +Hablando de estándares, tenemos: |
107 | 107 |
|
108 | | -DOM specification |
109 | | -: Describes the document structure, manipulations and events, see <https://dom.spec.whatwg.org>. |
| 108 | +La especificación del DOM |
| 109 | +: Describe la estructura del documento, las manipulaciones y los eventos, consulte <https://dom.spec.whatwg.org>. |
110 | 110 |
|
111 | | -CSSOM specification |
112 | | -: Describes stylesheets and style rules, manipulations with them and their binding to documents, see <https://www.w3.org/TR/cssom-1/>. |
| 111 | +La especificación del CSSOM |
| 112 | +: Describe las hojas de estilo y las reglas de estilo, las manipulaciones con ellas y su vinculación a los documentos, consulte <https://www.w3.org/TR/cssom-1/>. |
113 | 113 |
|
114 | | -HTML specification |
115 | | -: Describes the HTML language (e.g. tags) and also the BOM (browser object model) -- various browser functions: `setTimeout`, `alert`, `location` and so on, see <https://html.spec.whatwg.org>. It takes the DOM specification and extends it with many additional properties and methods. |
| 114 | +La especificación del HTML |
| 115 | +: Describe el lenguaje HTML (por ejemplo, etiquetas) y también el BOM (modelo de objeto del navegador) -- varias funciones del navegador: `setTimeout`, `alert`, `location`, etc., consulte <https://html.spec.whatwg.org>. Toma la especificación DOM y la extiende con muchas propiedades y métodos adicionales. |
116 | 116 |
|
117 | | -Now we'll get down to learning DOM, because the document plays the central role in the UI. |
| 117 | +Ahora nos ocuparemos de aprender DOM, porque el documento juega el papel central en la interfaz de usuario. |
118 | 118 |
|
119 | | -Please note the links above, as there's so much stuff to learn it's impossible to cover and remember everything. |
| 119 | +Ten en cuenta los enlaces anteriores, ya que hay tantas cosas que aprender que es imposible cubrir y recordar todo. |
120 | 120 |
|
121 | | -When you'd like to read about a property or a method, the Mozilla manual at <https://developer.mozilla.org/en-US/search> is a nice resource, but reading the corresponding spec may be better: it's more complex and longer to read, but will make your fundamental knowledge sound and complete. |
| 121 | +Cuando desees leer sobre una propiedad o un método, el manual de Mozilla en <https://developer.mozilla.org/es/search> es un buen recurso, pero leer las especificaciones correspondientes puede ser mejor: es más complejo y más para leer, pero hará que su conocimiento de los fundamentos sea sólido y completo. |
0 commit comments