The web browser automatically reads the script code written in .js file and considers the code as if it is written between opening <script> tag and closing </script> tag.
Now suppose we want the same fancy navigation menus on every web page of the website. What will you do?
First, we will have to do a lot of work for copying and pasting the same code over and over again. Especially, when we have a website with hundreds of pages.
Program code 1:
By default, the browser looks for any externally referenced file in the same folder as .html file is running.
Program code 2:
<head> <script src = "https://www.scientecheasy.com/myScript.js"></script> </head>
A URL is a path to the file located on the web server. There are three types of path:
- Absolute path
- Root-relative path
- Document-relative path
a) Absolute path: An absolute path is like a postal address that contains all the information required for web browser to locate a file anywhere in the world. It consists of http://, hostname, folder, and name of the file.
b) Root-relative path: A root-relative path is an address where a file is located relative to top-level folder or root folder of the site. It does not include http:// or domain name.
An easy way to create a root-relative path is that first take an absolute path and strip off https:// and host name. For example, https://www.scientecheasy.com/index.html can be written as root-relative URL is /index.html.
If folder scripts is located inside another folder named javaS, the path to the same file would be different, like this: ../scripts/myScript.js.
The ../ means climb up out of javaS folder, while /scripts/myScript.js means go to scripts folder and get the file myScript.js.
Important Tips to Use the Best URL Type
Here, there are some important tips on which URL type should be to use. They are as follows:
1. If the file is not located on the same sever as website, must use an absolute path because it is only the type that can point to another website.
3. Document relative path is the best to use when we are using local host in own computer without aid of web server.
The browser download the file only once that reduces the loading time of web page and also reduces bandwidth usage.
Thanks for reading!!!
Next ⇒ What is Scripting Language⇐ Prev Next ⇒