从JSON配置文件加载到HTML文件

Loading from a JSON configuration file into an HTML file?

本文关键字:HTML 文件 加载 JSON 配置文件      更新时间:2023-09-26

我是一个Javascript新手,所以我知道我想要不可能的。

我有一个看起来像这样的页面:

<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>

正如您所看到的,我在相同的静态位置包含了许多文件。HTML文件可能会被其他人以不同的方式使用,他们包括来自不同静态位置的文件,所以我想引入一个config.json文件,在那里可以指定这个和其他东西,例如:

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

这将以某种方式加载到我的页面中,我的脚本包含将是这样的:

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

…这当然不是正确的语法…但基本上,我正在寻找一种方法,在标题script标签的可变信息,基于JSON文件中提供的信息。

这样的事情有可能吗?

可以动态创建<script>标签。

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

裁判:http://unixpapa.com/js/dyna.html