Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  173] [ 4]  / answers: 1 / hits: 24733  / 10 Years ago, sat, november 8, 2014, 12:00:00

I'm trying to use an external JavaScript file in order to write Hello World into a HTML page.



However for some reason it does not work, I tried the same function and commands inline and it worked, but not when it's using an external JavaScript file. The part I commented out in the JS file was the previous method I was trying to use. Those lines of could worked when I ran the script from the header, and inline. Thanks



Html file:



<html>

<head>
</head>

<body>

<p id=external>

<script type=text/javascript src=hello.js>
externalFunction();
</script>
</p>

<script type=txt/javascript src=hello.js></script>

</body>

</html>


JavaScript file



function externalFunction() 
{
var t2 = document.getElementById(external);

t2.innerHTML = Hello World!!!

/*document.getElementById(external).innerHTML =
Hello World!!!;*/

}

More From » html

 Answers
3

In general, you want to place your JavaScript at the bottom of the page because it will normally reduce the display time of your page. You can find libraries imported in the header sometimes, but either way you need to declare your functions before you use them.



http://www.w3schools.com/js/js_whereto.asp



index.html



<!DOCTYPE html>
<html>

<head>
<!-- You could put this here and it would still work -->
<!-- But it is good practice to put it at the bottom -->
<!--<script src=hello.js></script>-->
</head>

<body>

<p id=external>Hi</p>

<!-- This first -->
<script src=hello.js></script>

<!-- Then you can call it -->
<script type=text/javascript>
externalFunction();
</script>

</body>

</html>


hello.js



function externalFunction() {
document.getElementById(external).innerHTML = Hello World!!!;
}


Plunker here.



Hope this helps.


[#68861] Thursday, November 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Tue, Feb 12, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;