Why people place Javascript in external files
- to use the same Javascript on many pages and don't want to rewrite Javascript code on every page, it is simpler to have one Javascript function code in one place (one .js file) then in many HTML files
- to get more organized and easiest to maintain code
- HTML page is smaller in size, making it load faster
- separates the JavaScript from the HTML to get better Search Engine Optimization (SEO), Javascript will not get higher PageRank
- they are forced to move js off the page (for example blogger users have problem to use javascript in blogger editor, or some similar restrictions)
How to add Javascript in external file
- First, you must make .js file. File must have extension .js
- write Javascript function (or functions) in file and save file
Sample TestJs.jsfunction Hello()
{
alert("Hello");
} - now we can make a call to javascript function from HTML file, let's assume that the .js file is in the same directory as the HTML file in which we are going to call javascript function
Sample HTML file : TestCall.html<html>
<head>
<script src="TestJs.js" type="text/javascript">
</script>
</head>
<body>
<input type="button" onclick="Hello()" value="Hello!">
</body>
</html> - that is it, if those two file are in same directory when user click on Hello button javascript Hello function (which is in js file) will be called from HTML file and will be executed
External Javascript in blogger post
Demonstration:
To use javascript inside blogger post you have follow next steps:
- save javascript function in js file (like described in previous chapter)
Sample TestJs.jsfunction Hello()
{
alert("Hello");
} - on blogspot (blogger) there is no option to upload js file (or file of any other type) so you need to find where to upload javascript file
- you can find instructions how to upload javascript file by following this link, take a look at Google Groups chapter
- in blogger post add code to use remote javascript
Use this:<script src="[URL OF AN EXTERNAL SCRIPT]" type="text/javascript"></script>
Example for uploaded javascript file on Google Groups:<script src="http://everything-about-blogging.googlegroups.com/web/TestJs.js?hl=en&gda=bUe-djsAAAATLYFRxG7MFqGWBWh2VvtrqIEbF7jzfKsOTBbDD3S6g8oRXZrtFiBTuJ69H91AzQAGRdr3QrylPkw2aRbXD_gF&gsc=CJY8-AsAAABni9lzDVHuoDw_bqXODZJz" type="text/javascript"></script>
- add code in blogger post that call JavaScript function
<input type="button" onclick="Hello()" value="Hello!">
- now you have blogger post which call javascript function from external file