How to link an external JavaScript file
In this tutorial, we show you how to link an external JavaScript file (file extension end with .js) to web page.
Note
In HTML, you can either embed JavaScript on web page or external JavaScript file, or implemented both ways together.
In HTML, you can either embed JavaScript on web page or external JavaScript file, or implemented both ways together.
1. External JavaScript file
Create a new file end with “.js” file extension, and put JavaScript code inside. That’s all, you just created an external JavaScript file 🙂
//file : hello.js
function sayHelloToThisPerson(name){
alert('hello : ' + name);
}
//run above js function when this js is loaded
sayHelloToThisPerson('mkyong');
2. Include it in web page
To include above hello.js
file in your web page, add a new <script>
with src
attribute :
<html>
<head></head>
<body>
<h1>JavaScript is funny</h1>
<script type="text/javascript" src="hello.js"></script>
</body>
</html>
P.S Make sure the “src” attribute is pointing to the correct external js file path.
3. Demo
Performance
You can put “script” tag inside the “head” or “body” tag, however, to make your page load faster, it’s always recommended to put the “script” tag at the end of your page content.
You can put “script” tag inside the “head” or “body” tag, however, to make your page load faster, it’s always recommended to put the “script” tag at the end of your page content.
Download Source Code
Download it – Link-External-JavaScript-File-Example.zip (1 KB)
Thanks a Lot… Couldn’t find an easier explanation and such an easy to follow sample anywhere. Exactly wat i needed!!
God bless you my friend.
Can you please tell me how can i run a pop ad script code on onload page. i am using popads code on my site that run on onclick event i want to run that code on Onload page can you help about that issue
How to add it in jsp . i am using netbeans ide
Hi,I am a starter at javascript and I’m strugling with external javascript.
Please can u help me in the follwing:
//This is for 1 page//
var images=new Array();
images[0]=new Image();
images[0].src=”Bob1.jpg”;
images[1]=new Image();
images[1].src=”Bob2.jpg”;
images[2]=new Image();
var step=0;
function slide()
{
document.images.slideImage.src = images[step].src;
if (step<2)
{
step++;
}
else{
step = 0;
}
}
window.onload = setInterval(slide, 2000);
}
//…and this for another page//
window.onload = init;
function init(){
var button = document.getElementById("enterNameButton");
button.onclick = handleButtonClick;
}
function handleButtonClick() {
var textInput = document.getElementById("NameTextInput");
var Name = textInput.value;
alert("Hello " + Name);
}
So I want both to work but they do not work, but if I put only one of them in the js file it works.
Please help me to find out the problem.
Many thanks
If we want to keep javascript files in a folder in eclipse..then how do we link the same from a jsp page …I am doing my project in Eclipse..
Thank You..