I hava a folder tests, were all my tests are in. And i have a folder were all my programm code is in.
- TestsFolder
- ->Testfolder
-->test.js
CodesFolder
- ->Folder1
- -->code.js
Now i want to include the code.js into test.js.
I hava a folder tests, were all my tests are in. And i have a folder were all my programm code is in.
-->test.js
CodesFolder
Now i want to include the code.js into test.js.
Relative path:
Path depends on the current file directory. For example:
index.html
TestFolder \
|- test.js
CodeFolder \
|- code.js
innerPages \
|- inner-page.html
|- another-page.html
If the browser currently running the file named inner-page.html
, you can access the code.js with relative path "../CodeFolder/code.js
". The ../
means "parent directory".
You can use multiple times "parent directory" - ../../../SomeFolder/somefile.js
= go 3 directories up, and then find the SomeFolder
and the file somefile.js
.
Absolute path:
It means that you access the root folder (if server run your files, it means the server public folder). Absolute paths starts with "/
". For example:
The absolute path: "/CodeFolder/code.js
" will access the code.js
file regardless from where you try to access it.
If the browser currently running index.html
. The above absolute path will access the code.js
. And if it currently running inder-page.html
This absolute path will access code.js
again.
Keep in mind that if this is a client-side project and it runs on the browser, the good practice is to use absolute paths instead of relative.
Imagine that you use code.js
into index.html
and all innerPages
. In the future you need to restructure the folders of the project somehow. For example you need to add sub-directory in innerPages
directory.
index.html
TestFolder \
|- test.js
CodeFolder \
|- code.js
innerPages \
|- user-pages \
|- inner-page.html
|- another-page.html
|- admin-pages \
|- ...
What's happening if you are used realtive paths? For example:
You are into inner-page.html
and you are used this path: "../CodeFolder/code.js"
.
This path will be incorrect in this case.
But if you using Absolute path... For example:
"/CodeFolder/code.js"
- It will still work, because the "/"
means the root directory. No matter where are you now, this path will search for CodeFolder
in your root directory.
Load the script
As @Krzysztof Trzos noted, you can use jQuery's getScript() function to easy load the script from another script. Or you can see the full answer he commented for non jquery way.