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?
codeninja.sj
  • 3,452
  • 1
  • 20
  • 37
  • 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. – Yeldar Kurmangaliyev Aug 14 '15 at 10:53
  • thanks @YeldarKurmangaliyev, but still I'm confused why they are referring another javascript library by its relative path!!! – codeninja.sj Aug 14 '15 at 11:02
  • @codeninja thanks for the upvote – Domain Aug 14 '15 at 13:07

3 Answers3

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.

Gerard van Helden
  • 1,601
  • 10
  • 13
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

Community
  • 1
  • 1
DieVeenman
  • 457
  • 1
  • 3
  • 18
0

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

Domain
  • 11,562
  • 3
  • 23
  • 44