carmenism
carmenism

Reputation: 1098

Loading from a JSON configuration file into an HTML file?

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?

Upvotes: 1

Views: 5336

Answers (1)

abhi
abhi

Reputation: 53

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

Upvotes: 1

Related Questions