1

I'm a Javascript novice, so for all I know I want the impossible.

I have a page that looks something like this:

<html>
  <head>
    <meta charset="utf-8" />
    <script src="//static.foo.com/x/js/file1.js"></script>
    <script src="//static.foo.com/x/js/file2.js"></script>
    ...
    <script src="//static.foo.com/x/js/file10.js"></script>
  </head>
  <body>
    ...
  </body>
</html>

As you can see I have many included files at the same static location. It's possible that the HTML file might be used in a different way by someone else where they include the files from a different static location, so I'd like to introduce a config.json file where this and other things can be specified, e.g.:

{
  "streamingApiLocation": "//stream.something.com/",
  "staticAssetLocation": "//static.foo.com/x/", 
  "authApiLocation": "//auth.something.com/"
}

Somehow this would be loaded into my page, and my script inclusions would be something like:

    <script src="config.staticAssetLocation + js/file1.js"></script>
    <script src="config.staticAssetLocation + js/file2.js"></script>
    ...
    <script src="config.staticAssetLocation + js/file10.js"></script>

...this of course is not proper syntax... But basically I'm looking for a way to have variable information in script tags in the header, based on information provided in a JSON file.

Is something like this even remotely possible?

carmenism
  • 1,087
  • 3
  • 12
  • 31
  • not possible like that. `src` isn't javascript code. it's a URI. you could have another script GENERATE new ` – Marc B Aug 23 '16 at 17:51
  • Take a look at a javascript framework, many of them have dependency management, and help you take care of basic tasks like this. I'd recommend angularJS as a good place to start – Mike Aug 23 '16 at 17:51
  • Check out this [answer](http://stackoverflow.com/a/950146/4434366) it may help. – Wild Beard Aug 23 '16 at 17:52
  • You should just concatenate and minify your files, there are many libs available to do that for you, e.g. with gulp or grunt – baao Aug 23 '16 at 17:56
  • Also keep in mind that you may run in to cross-domain restrictions given your example. http://stackoverflow.com/questions/9222822/why-do-browser-apis-restrict-cross-domain-requests – xDaevax Aug 23 '16 at 17:59

1 Answers1

1

You can create a <script> tag dynamically.

   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'helper.js';
   head.appendChild(script);

Ref: http://unixpapa.com/js/dyna.html

abhi
  • 53
  • 8
  • 1
    This will not work as expected if the dynamically added script tag is hosted on a resource external to the source domain. – xDaevax Aug 23 '16 at 18:00
  • Thanks. This answers how to make a script tag dynamically, but how would I load the configuration file into the page? – carmenism Aug 29 '16 at 17:39