JavaScript Tips #5 : Important Tips for Using JavaScript
Tip #1 : <script> tag is used to include JavaScript
We can use <script> tag inside HTML statement to include your JavaScript Statement to include in a webpage.
<script> // All Your Javascript Code goes // between the opening and closing // script tags. </script>
Tip #2 : <script> tag can be placed inside <head> or <body>
- Ideally we place JS code inside <head> tag. but there is no such rule which state the position of the <script> tag in HTML document.
- JS Code Written outside the JS method will be rendered and can affect the rendering of the page.
<html> <head> <script type="text/javascript"> document.write("<p>" + Date() + "</p>"); </script> </head> <body> <script type="text/javascript"> document.write("<p>" + Date() + "</p>"); </script> </body> </html>
will print following output on the screen -
Tue Nov 01 2012 7:15:35 GMT+0530 (India Standard Time) Tue Nov 01 2012 7:15:35 GMT+0530 (India Standard Time)
Tip #3 : Complete JS code can be combination of JS code from head and body
<html> <head> <script type="text/javascript"> var num1 = 10 + 20; </script> </head> <body> <script type="text/javascript"> document.write("<p>" + num1 + "</p>"); </script> </body> </html>
Tip #4 : Src Attribute may have Relative Path
We can specify relative path to the “src” attribute of the <script> tag. Script tag with src attribute specify that the JS code is present at different source.
<script src="path/sample.js"></script>
Or by specifying absolute path -
<script src="http://wwww.xyz.com/js/sample.js"></script>