Html link execute script

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

JavaScript is a scripting language that is widely used to add dynamic functionality to a web page, alongside HTML and CSS. User triggered events, animations, and content updates are among some of the features on a web page that are powered by JavaScript. In order to use JavaScript on an HTML web page, you must use the tag to either write your JavaScript code directly in your HTML markup or to link to an external JavaScript file. This guide shows you how to use the tag to link JavaScript to an HTML page. You also learn about tag attributes that help you optimize your web page’s loading time.

The tag is used to add JavaScript to an HTML web page. The following sections further explain how the tag behaves when added to HTML markup and the different ways you can use it to add JavaScript to a web page.

Читайте также:  Python entries in list

What is a Tag?

The tag can be used to embed JavaScript into a web page in the following two ways:

  • Writing JavaScript code directly within an opening and closing tags.
  • Referencing the path to a JavaScript file using the tag’s src attribute.

In both cases, when the HTML page loads, the web browser executes any JavaScript that it finds, in sequential order. There are two useful principles to keep in mind when using the tag:

  • The JavaScript contained within or referenced by tags is executed immediately when its portion of the page loads. So, a tag placed within a page’s tag executes before the HTML body. A tag placed just before the end of the closing tag, on the other hand, executes after everything else on the page has loaded and rendered.
  • The JavaScript used in your HTML markup defines functions and variables in the global scope. This means that if your web page has two tags — say, one at the beginning and one at the end — they can reference the same functions and variables. Keep in mind that the code still follows the ordering described in the point above. For that reason, a script at the beginning of a web page cannot reference a variable assigned in a script at the end of the web page.

How to Add JavaScript to HTML

You can add JavaScript to your HTML markup by embedding JavaScript code between opening and closing tags. For example, to add an alert box to an HTML page with a message that reads The script is working , add the following code to your HTML markup:

  

This example adds the JavaScript code directly to the HTML markup.

Читайте также:  Java swing text area

The next example demonstrates the tag contained within the body of an HTML page. As the browser sequentially executes the HTML, when it encounters the tag, it executes the JavaScript within the tag. The JavaScript adds an event listener to the button with id=»exampleButton» . If a user clicks on the button, an alert box presents the message passed as an argument to the alert() method.

In the example, the tag is placed after the tag. This is necessary because the JavaScript references the button element. If the JavaScript had been inserted any earlier, the button element would not yet have been created by the time the JavaScript executes.

Adding External JavaScript Files

As your JavaScript code gets more complicated, you are likely to prefer keeping it in an external JS file, rather than including the script directly in your HTML markup.

To include an external JavaScript file in HTML, you still use the tag. However, instead of adding JavaScript directly between the tags, you use the tag’s src attribute to point to an external JS file. The steps below give you a simple example that references an external JavaScript file HTML markup.

The steps below assume that you are developing a simple website on your local computer. Your site files are stored in a directory named example-site .

    In your example-site directory, add a new subdirectory named js_files . This directory stores any JavaScript files that are referenced by HTML files.

Defining Tag Attributes

Like all other HTML tags, the tag supports a series of attributes that you can use to further control the behavior of the JavaScript that is executed on a web page. The list below contains some of the most useful attributes.

  • The async attribute tells the browser to download the referenced JavaScript file as the web page is parsed. Once the file has downloaded, its contents are immediately executed.
  • The defer attribute tells the browser to download a JavaScript file as the web page is parsed. The file is only executed once the entire web page has loaded.
  • The type attribute is used to identify the kind of script that is referenced by the src attribute. However, since JavaScript has become the unambiguous standard, this attribute is rarely necessary anymore.
  • The charset attribute lets you define a different character set for an external JavaScript file. This attribute, though common to see, is considered deprecated since documents now must use UTF-8.

The sections below dive deeper into the two most useful tag attributes, async and defer . These sections discuss how these attributes can be used to improve a web page’s performance.

Async

Normally, when a browser encounters the tag with a linked JavaScript file, it stops loading the HTML in order to start downloading the referenced JavaScript file. Using the async attribute, it is possible to improve your web page’s performance by having the browser download the JavaScript file in the background while the page continues to load.

The example file’s script tag makes use of the async attribute.

It’s not always advisable to use the async attribute. For instance, if your script depends on certain elements not yet being rendered, or if the elements themselves depend on the script creating certain elements, async would likely be a problematic choice. When such cases are not a concern, async can help with your page’s load speed and user experience.

Defer

Like async , using defer tells the browser to download a linked JavaScript file in the background while the page continues to load. Unlike async , however, defer prevents the loaded script from being executed until the page has been fully rendered. This makes defer especially useful when your JavaScript code relies on one or more elements being rendered and available. Because defer ensures that the script only runs once the page has been loaded completely, you can be assured that the script does not run until all required elements are present on the page.

Conclusion

This guide covered the foundational information you need to start using JavaScript on your HTML pages. Whether you plan to embed a script or link a JavaScript file in your HTML, this guide outlined the steps needed to do so.

As a next step, you may be interested in looking at some of our other JavaScript tutorials. For instance, take a look at our Traversing the Document Object Model with JavaScript tutorial, our How to Modify the DOM with JavaScript tutorial, and our JavaScript Objects tutorial.

This page was originally published on Thursday, May 5, 2022.

Источник

Use JavaScript within a webpage

Take your webpages to the next level by harnessing JavaScript. Learn in this article how to trigger JavaScript right from your HTML documents.

Prerequisites: You need to be familiar with how to create a basic HTML document.
Objective: Learn how to trigger JavaScript in your HTML file, and learn the most important best practices for keeping JavaScript accessible.

About JavaScript

JavaScript is a programming language mostly used client-side to make webpages interactive. You can create amazing webpages without JavaScript, but JavaScript opens up a whole new level of possibilities.

Note: In this article we’re going over the HTML code you need to make JavaScript take effect. If you want to learn JavaScript itself, you can start with our JavaScript basics article. If you already know something about JavaScript or if you have a background with other programming languages, we suggest you jump directly into our JavaScript Guide.

How to trigger JavaScript from HTML

Within a browser, JavaScript doesn’t do anything by itself. You run JavaScript from inside your HTML webpages. To call JavaScript code from within HTML, you need the element. There are two ways to use script , depending on whether you’re linking to an external script or embedding a script right in your webpage.

Linking an external script

Usually, you’ll be writing scripts in their own .js files. If you want to execute a .js script from your webpage, just use with an src attribute pointing to the script file, using its URL:

script src="path/to/my/script.js"> script> 

Writing JavaScript within HTML

You may also add JavaScript code between tags rather than providing an src attribute.

script> window.addEventListener("load", () =>  console.log("This function is executed once the page is fully loaded"); >); script> 

That’s convenient when you just need a small bit of JavaScript, but if you keep JavaScript in separate files you’ll find it easier to

  • focus on your work
  • write self-sufficient HTML
  • write structured JavaScript applications

Use scripting accessibly

Accessibility is a major issue in any software development. JavaScript can make your website more accessible if you use it wisely, or it can become a disaster if you use scripting without care. To make JavaScript work in your favor, it’s worth knowing about certain best practices for adding JavaScript:

  • Make all content available as (structured) text. Rely on HTML for your content as much as possible. For example, if you’ve implemented a nice JavaScript progress bar, make sure to supplement it with matching text percentages inside the HTML. Likewise, your drop-down menus should be structured as unordered lists of links.
  • Make all functionality accessible from the keyboard.
    • Let users Tab through all controls (e.g., links and form input) in a logical order.
    • If you use pointer events (like mouse events or touch events), duplicate the functionality with keyboard events.
    • Test your site using a keyboard only.
    • At a minimum, leave a short message with like this:
    • Ideally, replicate the JavaScript functionality with HTML and server-side scripting when possible.
    • If you’re only looking for simple visual effects, CSS can often get the job done even more intuitively.
    • Since almost everybody does have JavaScript enabled,

    Learn more

    Found a content problem with this page?

    This page was last modified on Jun 30, 2023 by MDN contributors.

    Your blueprint for a better internet.

    Источник

Оцените статью