You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
The tutorialthat you're reading is about coreJavaScript,which is platform-independent. Later on, you'll learn aboutNode.JSand other platforms that use it.
El tutorialque estás leyendo trata sobre el núcleoJavaScript,que es independiente de la plataforma. Más adelante, aprenderás sobreNode.JSy otras plataformas que lo utilizan.
But we need a working environment to run our scriptsand, since this book is online, the browser is a good choice. We'll keep the amount of browser-specific commands (like `alert`)to a minimum so that you don't spend time on them if you plan to concentrate on another environment (like Node.JS).We'll focus on JavaScriptin the browser in the [next part](/ui)of the tutorial.
Pero necesitamos un entorno de trabajo para ejecutar nuestros scriptsy, dado que este libro está en línea, el navegador es una buena opción. Mantendremos la cantidad de comandos específicos del navegador (como `alert`)a un mínimo para que no dediques tiempo a ellos si planeas concentrarte en otro entorno (como Node.JS).Nos centraremos en JavaScripten el navegador en la [siguiente parte](/ui)del tutorial.
So first, let's see how we attach ascript to a webpage. For server-side environments (like Node.JS),you can execute thescriptwith a command like `"node my.js"`.
Entonces, primero, veamos cómo adjuntamos un script auna página web. Para entornos del lado del servidor (como Node.JS),puedes ejecutar elscriptcon un comando como `"node my.js"`.
##The"script" tag
##La etiqueta"script"
JavaScriptprograms can be inserted into any part of an HTMLdocument with the help of the `<script>` tag.
Los programas deJavaScriptse pueden insertar en cualquier parte de un documento HTMLcon la ayuda de la etiqueta `<script>`.
For instance:
Por ejemplo:
```html run height=100
<!DOCTYPE HTML>
<html>
<body>
<p>Before the script...</p>
<p>Antes del script...</p>
*!*
<script>
alert( 'Hello, world!' );
alert( '¡Hola, mundo!' );
</script>
*/!*
<p>...After the script.</p>
<p>...Después del script.</p>
</body>
</html>
```
```online
You can run the example by clicking the"Play"button in the right-top corner of the box above.
Puedes ejecutar el ejemplo haciendo clic en el botón"Play"en la esquina superior derecha del cuadro de arriba.
```
The`<script>`tag contains JavaScriptcode which is automatically executed when the browser processes the tag.
La etiqueta`<script>`contiene código JavaScriptque se ejecuta automáticamente cuando el navegador procesa la etiqueta.
##Modern markup
##Marcado moderno
The`<script>`tag has a few attributes that are rarely used nowadays but can still be found in old code:
La etiqueta`<script>`tiene algunos atributos que rara vez se usan en la actualidad, pero aún se pueden encontrar en código antiguo:
:The old HTML standard, HTML4,required ascriptto have a`type`.Usually it was`type="text/javascript"`.It's not required anymore. Also, the modern HTMLstandard, HTML5,totally changed the meaning of this attribute. Now, it can be used for JavaScript modules. But that's an advanced topic; we'll talk about modules in another part of thetutorial.
El atributo`type`: <code><script <u>type</u>=...></code>
:El antiguo estándar HTML, HTML4,requería que unscripttuviera un`type`.Por lo general, era`type="text/javascript"`.Ya no es necesario. Además, el estándar HTMLmoderno, HTML5,cambió totalmente el significado de este atributo. Ahora, se puede utilizar para módulos de JavaScript. Pero eso es un tema avanzado, hablaremos sobre módulos en otra parte deltutorial.
:This attribute was meant to show the language of thescript.This attributenolonger makes sense becauseJavaScriptis the default language. There is no need to use it.
El atributo`language`: <code><script <u>language</u>=...></code>
:Este atributo estaba destinado a mostrar el lenguaje delscript.Este atributo yanotiene sentido porqueJavaScriptes el lenguaje predeterminado. No hay necesidad de usarlo.
Comments before and after scripts.
:In really ancient books and guides, you may find comments inside`<script>` tags, like this:
Comentarios antes y después de los scripts.
:En libros y guías realmente antiguos, puede encontrar comentarios dentro de las etiquetas`<script>`, como el siguiente:
```html no-beautify
<script type="text/javascript"><!--
...
//--></script>
```
This trick isn't used in modern JavaScript. These comments hidJavaScriptcode from old browsers that didn't know how to process the `<script>` tag. Since browsers released in the last15years don't have this issue, this kind of comment can help you identify really old code.
Este truco no se utiliza en JavaScript moderno. Estos comentarios ocultaban el códigoJavaScriptde los navegadores antiguos que no sabían cómo procesar la etiqueta `<script>`. Dado que los navegadores lanzados en los últimos15años no tienen este problema, este tipo de comentario puede ayudarte a identificar códigos realmente antiguos.
##External scripts
##Scripts externos
If we have a lot of JavaScript code, we can put it into a separate file.
Si tenemos un montón de código JavaScript, podemos ponerlo en un archivo separado.
Script files are attached toHTMLwith the`src` attribute:
Los archivos de script se adjuntan aHTMLcon el atributo`src`:
```html
<script src="/path/to/script.js"></script>
```
Here, `/path/to/script.js`is an absolute path to thescriptfile (from the site root).
Aquí, `/path/to/script.js`es una ruta absoluta al archivo descript(desde la raíz del sitio).
You can also provide a relative path from the current page. For instance, `src="script.js"`would mean a file`"script.js"`in the current folder.
También puede proporcionar una ruta relativa desde la página actual. Por ejemplo, `src="script.js"`significaría un archivo`"script.js"`en la carpeta actual.
Para adjuntar varios scripts,usa varias etiquetas:
```html
<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>
…
```
```smart
As a rule, only the simplestscriptsare put intoHTML.More complex ones reside in separate files.
```smart header="Ten en cuenta:"
Como regla general, solo losscriptsmás simples se colocan en elHTML.Los más complejos residen en archivos separados.
The benefit of a separate file is that the browser will download it and store it in its [cache](https://en.wikipedia.org/wiki/Web_cache).
La ventaja de un archivo separado es que el navegador lo descargará y lo almacenará en [caché](https://es.wikipedia.org/wiki/Cach%C3%A9_(informática)).
Other pages that reference the samescriptwill take it from the cache instead of downloading it, so the file is actually downloaded only once.
Otras páginas que hacen referencia al mismoscriptlo tomarán del caché en lugar de descargarlo, por lo que el archivo solo se descarga una vez.
That reduces traffic and makes pages faster.
Eso reduce el tráfico y hace que las páginas sean más rápidas.
```
````warn header="If`src` is set, the scriptcontent is ignored."
A single`<script>`tag can't have both the `src`attribute and code inside.
````warn header="Si se establece`src`, el contenido del scriptse ignora."
Una sola etiqueta`<script>`no puede tener el atributo `src`y código dentro.
This won't work:
Esto no funcionará:
```html
<script *!*src*/!*="file.js">
alert(1); //the content is ignored, because srcis set
alert(1); //el contenido se ignora, porque srcse establece
</script>
```
We must choose either an external`<script src="…">`or a regular `<script>`with code.
Debemos elegir un`<script src="…">`externo o un `<script>`normal con código.
The example above can be split into two scriptsto work:
El ejemplo anterior se puede dividir en dos scriptspara que funcione:
```html
<script src="file.js"></script>
Expand All
@@ -124,11 +124,12 @@ The example above can be split into two scripts to work:
```
````
##Summary
##Resumen
-We can use a `<script>`tag to add JavaScriptcode to a page.
-The`type`and `language`attributes are not required.
-A scriptin an external file can be inserted with `<script src="path/to/script.js"></script>`.
-Podemos usar una etiqueta `<script>`para agregar código JavaScripta una página.
-Los atributos`type`y `language`no son necesarios.
-Un scripten un archivo externo se puede insertar con `<script src="path/to/script.js"></script>`.
There is much more to learn about browser scripts and their interaction with the webpage. But let's keep in mind that this part of the tutorial is devoted to the JavaScript language, so we shouldn't distract ourselves with browser-specific implementations of it. We'll be using the browser as a way to run JavaScript, which is very convenient for online reading, but only one of many.
Hay mucho más que aprender sobre los scripts del navegador y su interacción con la página web. Pero tengamos en cuenta que esta parte del tutorial está dedicada al lenguaje JavaScript, por lo que no debemos distraernos con implementaciones específicas del navegador. Usaremos el navegador como una forma de ejecutar JavaScript, lo cual es muy conveniente para la lectura en línea, pero es solo una de muchas.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.