1

I have recently got a chance to explore one famous JavaScript library; In that library, I have found one strange way of referring JavaScript library from HTML page.

The application folder structure looks like this,

enter image description here

index.html contains the reference of subroot.js;

index.html

<head>
   <title>Index</title>
   <script src="js/subroot.js"></script>
</head>

subroot.js only contains the following code (i.e.,the relative path of root.js)

subroot.js

../../js/root.js

When I try to run the index.html, i get syntax error in the first line of subroot.js

Questions:

  1. Is it right way to refer another javascript library by its relative path?
  2. If yes, Why I get error message on the web page?
3
  • 3
    If your questions is if it is a correct JS syntax, then, obviously, no. There are many ways to append one JS file to HTML page from another and simply writing a relative path to it is not one of them. Commented Aug 14, 2015 at 10:53
  • thanks @YeldarKurmangaliyev, but still I'm confused why they are referring another javascript library by its relative path!!! Commented Aug 14, 2015 at 11:02
  • @codeninja thanks for the upvote Commented Aug 14, 2015 at 13:07

3 Answers 3

2

JavaScript by itself doesn't support loading files or referring paths. You need a module loader of some kind to achieve what you want. With the new version of the standard (ECMAScript 6) there is something called "imports" which you might find useful. I have experience using JSPM and the SystemJS module loader, which makes it pretty easy to connect the dots.

However, without using any additional tools you should just inject another script tag in your HTML.

Sign up to request clarification or add additional context in comments.

Comments

0

Just reference root.js in the HTMl file not in the Subroot.js file, you can't reference another .js file from a .js file as far as I know.

<script src="../js/root.js"></script>

See Link

Comments

0

write this in subroot.js file var x = document.createElement('script'); x.src = '../../js/root.js'; document.getElementsByTagName("head")[0].appendChild(x);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.