ways to add JavaScript to a web page

www.l‮tua‬turi.com
ways to add JavaScript to a web page

There are several ways to add JavaScript to a web page:

  1. Inline JavaScript: You can add JavaScript directly to an HTML element by using the script tag and specifying the JavaScript code as the value of the script tag's innerHTML attribute. For example:
<button onclick="document.getElementById('myDiv').innerHTML = 'Hello World!'">Click me</button>
  1. External JavaScript: You can also include JavaScript in a separate file and reference it in the HTML file using the script tag and specifying the path to the JavaScript file using the src attribute. For example:
<script src="/path/to/script.js"></script>
  1. Async and Defer: You can use the async and defer attributes to control the loading of the JavaScript file. The async attribute tells the browser to download the file asynchronously, while the defer attribute tells the browser to download the file and wait until the HTML parser has finished before executing the script.

  2. Adding JavaScript to a specific element: You can also add JavaScript to specific elements by using their id or class attributes and specifying the JavaScript code as the value of the element's onclick, onmouseover, or other event attributes. For example:

<button id="myButton" onclick="document.getElementById('myDiv').innerHTML = 'Hello World!'">Click me</button>
  1. Adding JavaScript using jQuery: You can also use the jQuery library to add JavaScript to a web page. For example:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
    $('#myButton').click(function() {
      $('#myDiv').html('Hello World!');
    });
  });
</script>
Created Time:2017-10-16 14:38:55  Author:lautturi