脚本和链接标记是否在javascript中起作用?

时间:2019-03-14 10:27:01

标签: javascript reactjs

在这里我创建新项目在我的新项目index.html中,我为项目构建编写了以下代码。现在我有两个用于运行项目的命令

1. npm run admin-watch
2. npm run web-watch

现在,如果扩展名为admin,我想明智地构建项目if-else条件,然后如果条件else则允许构建项目。但是,如果使用JavaScript,如何在内部允许多个脚本标签和链接标签?

index.html

let pathname = window.location.pathname;
let splitPath = pathname.split('/')[1];
if(splitPath === admin){
  <link rel="stylesheet" href="/build/web/css/style.css">
  <script src="/build/web/js/index.js" type="text/javascript"></script>
  <script src="/build/web/js/manifest.js" type="text/javascript"></script>
  <script src="/build/web/js/vendor.js" type="text/javascript"></script>
}else{
  <link rel="stylesheet" href="/build/admin/css/admin.css">
  <script src="/build/admin/js/admin.js" type="text/javascript"></script>
  <script src="/build/admin/js/manifest.js" type="text/javascript"></script>
  <script src="/build/admin/js/vendor.js" type="text/javascript"></script>
}

1 个答案:

答案 0 :(得分:0)

有一种解决方法,可以在运行时调用一个函数,该函数根据您的情况插入适当的脚本标签:

function loadMyScripts(){
    let pathname = window.location.pathname;
    let splitPath = pathname.split('/')[1];
    if(splitPath === admin){
      let link = document.createElement('link');
      link.rel = "stylesheet";
      link.href = "/build/web/css/style.css"
      document.head.appendChild(link);

      let scriptOne = document.createElement('script');
      script.src = "/build/web/js/index.js";
      script.type = "text/javascript";
      document.head.appendChild(scriptOne);

      // the rest of the scripts have the same approach, just change src and type attribute
    }else{
      //create more element objects with other attributes and append them to the head as above
    }
}