Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call external javascript on window.load?

I want to put this in my website

<script type="text/javascript"> <!-- window.onload = hello; function
hello() { var name = prompt("What is your name", "") alert ( "Hello "
+ name + "! Welcome to my forum.") } </script>

but I dont want to put it in index but in separate file, let say hello.js

How can I call it from index file so when I click the index.html, it will immediately prompt for my name. (for example)

I put <script src="hello.js"></script> does not work.

like image 287
Wan Avatar asked Aug 12 '11 08:08

Wan


People also ask

How to call a function on page load in JavaScript?

To call a function on page load, use −. window.onload Example. You can try to run the following code to implement a JavaScript function on page load. Live Demo <!DOCTYPE html> <html> <body> <script> function alertFunction() { alert('ok'); } window.onload = alertFunction; </script> </body> </html>

How to include external JavaScript files dynamically after the page has loaded?

script.innerHTML = 'alert ("Inline script loaded!")' As you can see, it’s easy to create and append new script elements, allowing us to include any number of external JavaScript files dynamically after a page has loaded. The real challenge isn’t loading the file – it’s knowing when the file has finished loading.

How to create an external JavaScript file in HTML?

It increases the code re usability. <script type="text/javascript" src="external.js"></script> First create a JavaScript file and then save the file with .js extension. After that we can use src attribute of script tag to use this already created file. function show () { alert ("External JavaScript file."); }

Why do I get errors when using external code in JavaScript?

When using JavaScript, sometimes you will run into errors because the external code being used is placed above the HTML it is calling/manipulating. For this example, we have a HTML file that looks like this:


2 Answers

Your hello.js should look something like this:

window.onload = hello; 

function hello() { 
    var name = prompt("What is your name", "");
    alert("Hello " + name + "! Welcome to my forum."); 
}

and then the <script src="hello.js"></script> should work just fine.

like image 53
Andrius Virbičianskas Avatar answered Sep 27 '22 20:09

Andrius Virbičianskas


There shouldn't be much more to it than importing that script. But then, your script is all broken. Of course it won't work, unless your browser can interpret it. Take a look at javascript basics. On the first look, you don't seem to be using semicolons to delimit individual statements. Also, you have opened an HTML comment <!-- but you have never closed it...

like image 37
Peter Perháč Avatar answered Sep 27 '22 20:09

Peter Perháč