- JavaScript Where to Put
- In-line JavaScript
- JavaScript place on tag
- JavaScript place on tag
- External JavaScript
- Test on Console Panel (Browser Developer Tools)
- How To Add JavaScript to HTML
- Adding JavaScript into an HTML Document
- Working with a Separate JavaScript File
- Conclusion
- Tutorial Series: How To Code in JavaScript
- Where do you put your javascript?
- Solution 2
- Solution 3
- Solution 4
JavaScript Where to Put
JavaScript Where to Put. HTML script element offer to write JavaScript between opening tag. You can put JavaScript head or body section. Also you can write JavaScript external .js extension file.
Before we going ahead, let’s know JavaScript where to write.
In JavaScript Introduction lesson we referred to a in-line JavaScript code. It’s ok for a beginner but when the page content is largest It’s hard to maintain JavaScript mixed with HTML. And page content become follow the worst coding standard.
Instead of this in-line JavaScript, We should write JavaScript into separated section or separated file. You can write JavaScript,
- In-line JavaScript
- JavaScript place on tag
- JavaScript place on tag
- External JavaScript
- Test on Console Panel (Browser Developer Tools)
As per HTML specification type attribute must be specify with valid value «text/javascript» .
In-line JavaScript
You can write inline JavaScript statements for all HTML events.
JavaScript place on tag
You can write JavaScript directly body section inside opening tag.
Put JavaScript code at end of the body section is improve the page loading speed, Because HTML content loading is not blocking JavaScript code.
JavaScript place on tag
JavaScript write on head section inside opening tag.
Sometimes page content depend on this JavaScript code. So we need to load JavaScript code before the Body Section.
function user_fun()
External JavaScript
You can write JavaScript code on external file with .js extension . And linked with the main documents.
Benefit of external JavaScript file you can linked multiple document, when you edit JavaScript file effect to all linked document.
Using «src» attributes to find relative path of external .js file.
Test on Console Panel (Browser Developer Tools)
You can test JavaScript statement on console panel and return the output. Also console.log() method to print the values on console.
View Result : Open Console Panel (In Browser, press F12)
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.
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:
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:
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:
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.
Where do you put your javascript?
Putting all your js in one file can help performance (only one request versus several). And if you’re using a content distribution network like Akamai it improves your cache hit ratio. Also, always throw inline js at the very bottom of the page (just above the body tag) because that is executed synchronously and can delay your page from rendering.
And yes, if one of the js files you are using is also hosted at google, make sure to use that one.
Solution 2
Here’s my «guidelines». Note that none of these are formal, they just seem like the right thing to do.
All shared JS code lives in the SITE/javascripts directory, but it’s loaded in ‘tiers’
For site-wide stuff (like jquery, or my site wide application.js), the site wide layout (this would be a master page in ASP.net) includes the file. The script tags go at the top of the page.
There’s also ‘region-wide’ stuff (eg: js code which is only needed in the admin section of the site). These regions either have a common layout (which can then include the script tags) or will render a common partial, and that partial can include the script tags)
For less-shared stuff (say my library that’s only needed in a few places) then I put a script tag in those HTML pages individually. The script tags go at the top of the page.
For stuff that’s only relevant to the single page, I just write inline javascript. I try to keep it as close to it’s «target» as possible. For example, if I have some onclick js for a button, the script tag will go below the button.
For inline JS that doesn’t have a target (eg: onload events) it goes at the bottom of the page.
So, how does something get into a localised library, or a site-wide library?.
- The first time you need it, write it inline
- The next time you need it, pull the inline code up to a localised library
- If you’re referencing some code in a localized library from (approximately) 3 or more places, pull the code up to a region-wide library
- If it’s needed from more than one region, pull it up to a site-wide library.
A common complaint about a system such as this, is that you wind up with 10 or 20 small JS files, where 2 or 3 large JS files will perform better from a networking point of view. However, both rails and ASP.NET have features which handle combining and caching multiple JS files into one or more ‘super’ js files for production situations.
I’d recommend using features like this rather than compromising the quality/readability of the actual source code.
Solution 3
Yahoo!’s Exceptional Performance Team has some great performance suggestions for JavaScript. Steve Souders used to be on that team (he’s now at Google) and he’s written some interesting tools that can help you decide where to put JavaScript.
Solution 4
I try to avoid putting javascript functions on the rendered page. In general, I have an application.js (or root.js) that has generic functionality like menu manipulation. If a given page has specific javascript functionality, I’ll create a .js file to handle that code and mimic the dir structure on how to get to that file (also using the same name as the rendered file).
In other words, if the rendered page is in public/dir1/dir2/mypage.html, the js file would be in public/js/dir1/dir2/mypage.js. I’ve found this style works well for me, especially when doing templating on a site. I build the template engine to «autoload» my resources (css and js) by taking the request path and doing some checking for the css and js equivalents in the css and js directories on the root.