Script in head section

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.

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.

Читайте также:  Php split array by char

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.

Источник

Embedding JavaScript in HTML

An HTML document is made up of HTML elements, HTML element attributes, comments, special characters, and doctype. If you like to add presentational features to an HTML document you can attach css to an HTML document, to add dynamic user experience (e.g. popup, alert message, animations etc.) to an HTML document you can add JavaScipt to your HTML document.

If javascript is disabled in the browser property, even though an external script is attached or a script is written within tags in an HTML document, it becomes inactive.

Certain JavaScripts do not work with all the browsers and sometimes a script works on and above (or vice a versa) a particular version of a web browser.

The script Tag

The script is an HTML element. Html script element is used to enclose client side scripts like JavaScript within an HTML document.

There are four types of attributes in script element:

The language attribute is used to specify the scripting language and it’s version for the enclosed code. In the following example, JavaScript version is 1.2. If a specific browser does not support the said JavaScript version, the code is ignored. If you do not specify a language attribute, the default behavior depends on the browser version. The language attribute is deprecated in HTML 4.01.

This attribute specifies the location of an external script. This attribute is useful for sharing functions among many different pages. Note that external JavaScript files contain only JavaScript statements and files must have the extension .js.

If you set defer attribute, the browser delays the execution of the script or it changes the order of the execution of the script. This can improve the performance by delaying execution of scripts until the content of body is read and displayed by the browser.

This attribute specifies the scripting language. The scripting language is specified as a content type (e.g., «text/javascript» ). The attribute is supported by all modern browser.

The noscript tag

If any browser does not support the JavaScript code the alternate content placed within noscript tag is being executed.

Javascript in HTML document

There are two general areas in HTML document where JavaScript can be placed. First is between . section, another is specific location in . section. If you want to display a message ‘Good Morning’ (through the JavaScript alert command) at the time of page loading then you must place the script at the . section. In the following examples you will see the different location of tags in a HTML document.

Script in the Head

        

Script in the Body

          

Scripts in the Head and Body

           

Two Scripts in the Body

            

Note: Optionally, if your script is not required to be executed before the content of the body is displayed, and your script takes longer time to load objects, you can place your script at the end of the body element.

Double or Single Quotes in JavaScript

There is no preferred method, you can use either. If you use one form of the quote (either single or double) in the string, you may use other as the literal.

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

undefined and ReferenceError

Within the function, we first declare the name variable with the var keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of undefined, until we actually get to the line where we define the variable. We haven’t defined the variable yet on the line where we try to log the name variable, so it still holds the value of undefined.
Variables with the let keyword (and const) are hoisted, but unlike var, don’t get initialized. They are not accessible before the line we declare (initialize) them. This is called the «temporal dead zone». When we try to access the variables before they are declared, JavaScript throws a ReferenceError.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

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