Thursday 28 February 2013

JavaScript: how to use external files

   


As we already know, because we saw it in the past here on the web thought or elsewhere, we can use JavaScript snippet by placing the code in the head and/or the body of our documents.
However, it's good practise to create external JavaScript files, especially when we use standard functions all over our web site.

In this short article, we are going to see how to do it.

Creating our own JavaScript library is not that difficult.
What we basically want to do it here is: create an external .js file, embed it in our page and finally use a function from the external file.

Let's create the .js file.
To do so, we create a new file in the root of our web site. Like creating a new txt file, but with a different extension; we name the new file myJs.js. Open it with your favourite web editor and place the following code inside it:
function popUp() {
alert("Hello from the web thought")
}
Ok. Save and close the myJs.js file.

Now open a new html document and place the following snippet in the head section:
<script src="myJs.js"></script>
In the body of the document, just insert the following snippet:
<input type="button" onclick="popUp()" value="Click here!"> 
Just open the newly created html file with your favourite browser. The effect will be that when we click the button, an alert will popoup as expected.

The magic is basically done by embedding the popUp() function inside the web document by using the src="fileName" in the head of our document itself.

Just remember:
1) we use external files when we need to use specific functions all over the web site. Doing so we don't need to write the functions in every document;
2) we do not use the <script> tag inside the .js file: we just put the functions one after the other;
3) we can use external .js files to be placed in the head of our documents and even to be placed in the body of our documents (the script will be run when the page loads).

And that is all for today.
Hoping that I will find the time to write again next week...

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.