Where to use javascript code

How To Add JavaScript to HTML

JavaScript, also abbreviated to JS, is a programming language used in web development. As one of the core technologies of the web alongside HTML and CSS, JavaScript is used to make webpages interactive and to build web apps. Modern web browsers, which adhere to common display standards, support JavaScript through built-in engines without the need for additional plugins.

When working with files for the web, JavaScript needs to be loaded and run alongside HTML markup. This can be done either inline within an HTML document or in a separate file that the browser will download alongside the HTML document.

This tutorial will go over how to incorporate JavaScript into your web files, both inline into an HTML document and as a separate file.

Adding JavaScript into an HTML Document

You can add JavaScript code in an HTML document by employing the dedicated HTML tag that wraps around JavaScript code.

The tag can be placed in the section of your HTML or in the section, depending on when you want the JavaScript to load.

Читайте также:  Сортировка алфавиту массива php

Generally, JavaScript code can go inside of the document section in order to keep them contained and out of the main content of your HTML document.

However, if your script needs to run at a certain point within a page’s layout — like when using document.write to generate content — you should put it at the point where it should be called, usually within the section.

Let’s consider the following blank HTML document with a browser title of Today’s Date :

DOCTYPE html> html lang="en-US"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1"> title>Today's Datetitle> head> body> body> html> 

Right now, this file only contains HTML markup. Let’s say we would like to add the following JavaScript code to the document:

let d = new Date(); alert("Today's date is " + d); 

This will enable the webpage to display an alert with the current date regardless of when the user loads the site.

In order to achieve this, we will add a tag along with some JavaScript code into the HTML file.

To begin with, we’ll add the JavaScript code between the tags, signalling the browser to run the JavaScript script before loading in the rest of the page. We can add the JavaScript below the tags, for instance, as shown below:

DOCTYPE html> html lang="en-US"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1"> title>Today's Datetitle> script> let d = new Date(); alert("Today's date is " + d); script> head> body> body> html> 

Once you load the page, you will receive an alert similar to this:

JavaScript Alert Example

If we were modifying what is shown in the body of the HTML, we would need to implement that after the section so that it displays on the page, as in the example below:

DOCTYPE html> html lang="en-US"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1"> title>Today's Datetitle> head> body> script> let d = new Date(); document.body.innerHTML = "Today's date is " + d + ">" script> body> html> 

The output for the above HTML document loaded through a web browser would look similar to the following:

JavaScript Date Example

Scripts that are small or that run only on one page can work fine within an HTML file, but for larger scripts or scripts that will be used on many pages, it is not a very effective solution because including it can become unwieldy or difficult to read and understand. In the next section, we’ll go over how to handle a separate JavaScript file in your HTML document.

Working with a Separate JavaScript File

In order to accommodate larger scripts or scripts that will be used across several pages, JavaScript code generally lives in one or more js files that are referenced within HTML documents, similarly to how external assets like CSS are referenced.

The benefits of using a separate JavaScript file include:

  • Separating the HTML markup and JavaScript code to make both more straightforward
  • Separate files makes maintenance easier
  • When JavaScript files are cached, pages load more quickly

To demonstrate how to connect a JavaScript document to an HTML document, let’s create a small web project. It will consist of script.js in the js/ directory, style.css in the css/ directory, and a main index.html in the root of the project.

project/ ├── css/ | └── style.css ├── js/ | └── script.js └── index.html 

We can start with our previous HTML template from the section above:

DOCTYPE html> html lang="en-US"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1"> title>Today's Datetitle> head> body> body> html> 

Now, let’s move our JavaScript code that will show the date as an header to the script.js file:

let d = new Date(); document.body.innerHTML = "

Today's date is " + d + "

"

We can add a reference to this script to the section, with the following line of code:

script src="js/script.js">/script> 

The tag is pointing to the script.js file in the js/ directory of our web project.

Let’s consider this line in the context of our HTML file, in this case, within the section:

DOCTYPE html> html lang="en-US"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1"> title>Today's Datetitle> head> body> script src="js/script.js">script> body> html> 

Finally, let’s also edit the style.css file by adding a background color and style to the header:

body  background-color: #0080ff; > h1  color: #fff; font-family: Arial, Helvetica, sans-serif; > 

We can reference that CSS file within the section of our HTML document:

DOCTYPE html> html lang="en-US"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1"> title>Today's Datetitle> link rel="stylesheet" href="css/style.css"> head> body> script src="js/script.js">script> body> html> 

Now, with the JavaScript and CSS in place we can load the index.html page into the web browser of our choice. We should see a page that looks similar to the following:

JavaScript Date with CSS Example

Now that we’ve placed the JavaScript in a file, we can call it in the same way from additional web pages and update them all in a single location

Conclusion

This tutorial went over how to incorporate JavaScript into your web files, both inline into an HTML document and as a separate .js file.

Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers — for free! DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!

Tutorial Series: How To Code in JavaScript

JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.

Источник

🚀 How to Run JavaScript Code

In order to follow along with this course, you need to know how and where you run your JavaScript code. You have several options to run your first hello world programming:

Open your editor and create a file named index.js .

How to Run JavaScript from the Command Line

Running a JS program from the command line is handled by NodeJS. Start by installing NodeJS on local machine if necessary.

Now simply open the command line in the same directory as the index.js script you created (VS Code will do this automatically with the integrated terminal).

How to Run JavaScript from the Browser

When people think of “JavaScript”, they most often think of a web browser. You can run code in the browser by creating an HTML file that references the script. In our case, we used the defer option, which will execute the JS after the HTML file is finished loading.

Run a script from an HTML file

html>  head>  script defer src="./index.js">script>  head> html> 

Now simply open this HTML file on your local machine and open the developer console (next step) to see the output.

Inspect the Browser Console

In Chrome, you can open the developer console with Ctrl+Shift+J (Windows) or Ctrl+Option+J (Mac), or manually from the settings menu by selecting More Tools -> Developer Tools. The console allows you to run code in the browser, similar to how

Output of the browser console in Chrome

Run JavaScript with a Framework

It is worth mentioning that frameworks like React, Angular, Svelte, etc will take care of the building & running of your app automatically and provide framework-specific tooling and steps for running code. In the real world, you are more likely to use the tooling provided by the framework to run your code, as opposed to the basic methods shown in this couse.

Run JavaScript in a Sandbox

This course uses StackBlitz to run JS code examples in an isolated sandbox in the browser. This is a great option for sharing quick demos and issue reproductions 💡.

Источник

Where to place JavaScript code in the HTML file

Where to place JavaScript code in the HTML file

  1. Where to place JavaScript code in the HTML file?
  2. Advantages of external JavaScript over inline JavaScript.
Where to place JavaScript code in the HTML file?

JavaScript code will be executed immediately while the page loads into the browser. This is not always what we want the JavaScript code to run. Sometimes we want to execute a script when a page loads other times when the user triggers an event. There are various ways to include JS code in our HTML file.

  • Scripts in … section of HTML
  • Scripts in … section of HTML
  • Scripts in … and … sections of HTML
  • Scripts in an external file and then include in … section of HTML
Scripts in … section of HTML:

If we want the JavaScript code should be executed when it is called or when an event is triggered then we should keep it in the head section.

Example:
Output:

Where to place JavaScript code in the HTML file

Scripts in … section of HTML

If we want the script should be run when the page loads then we should keep the JavaScript program in the body section. If we place a script in the body section it will generate the content on the page.

Example:
  Hello    
Output:

JavaScripts in the Body Section of a HTML File

Scripts in … and … sections of HTML

We can place an unlimited number of scripts in the HTML file in the head or body section. So we can have the script in both the body and the head section also.

Example:
      
Output:

JavaScripts in both Head and Body Section of a HTML File

Scripts in an external file and then include in … section of HTML:

If we want to reuse a single script code on multiple pages then we can place the script in an external file. The script tag provides a method to store JavaScript in an external file and then include it into HTML files using the src attribute of the script tag. An external JavaScript file generally has a .js extension. It is good practice to places all JavaScript files into a single JS file.

The advantage of using an external JS file is that editing the script file has become easier as it can be done in one location, rather than editing the code in the script tags on each page containing the script.

Example: Using an external js file
External JS file (external.js)
Advantages of external JavaScript over inline JavaScript:

You will get the following advantages of using external JavaScript files over the inline JavaScript

Maintainability and Reusability: You can refer to the external JavaScript files on multiple pages without having to duplicate the code on every page. That means you can reuse the same JavaScript code on multiple pages. If you need to change something, then you need to change only in one place. As a result, maintenance will become easier.

Separation of Concerns: As we are storing the JavaScript file in a separate .js file, so it adheres to the separation of concerns design principle. In general, it is always a good practice to separate HTML, CSS, and JavaScript as it makes it easier to work with them. As well as it also allows multiple developers to work simultaneously.

Performance: The external JavaScript file can be cached by the browser, whereas the inline JavaScript on the page is loaded every time the page loads. So, you will get better performance with the external JavaScript file.

That’s it for today. Here, in this, I try to explain Where to place JavaScript code in the HTML file. In the next article, I am going to discuss JavaScript Comments and Statements in detail with Examples. I hope you enjoy this Where to place JavaScript code in the HTML file article.

Источник

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