节点ejs动态javascript加载

时间:2017-06-21 17:31:41

标签: javascript node.js ejs p5.js

所以我试图让路由文件传递一个需要包含在页面中的javascript文件列表,并让ejs构造头文件以包含这些脚本

我的路线档案

router.get('/:name', function(req,res, next) {
  res.render('templates/experiment', {
    name:req.params.name,
    extraScripts:experiments[req.params.name].extraScripts
  })
});

我的experiment.ejs

<head>
  <title><%= name %></title>
  <script src="../javascripts/p5/p5.js"></script>
  <script src="../javascripts/p5/addons/p5.dom.js"></script>
  <script src="../javascripts/p5/addons/p5.sound.js"></script>
  <% for(var i = 0; i < extraScripts.length; i++) { %>
    <script scr=<%= "../javascripts/" + extraScripts[i]%> ></script>
  <% }%>
  <script src=<%= "../javascripts/experiments/"+name + "/sketch.js"%>></script>
  <style> body {padding: 0; margin: 0;} </style>
</head>

现在当我加载页面时,我可以看到脚本标记就好了,但它没有进行额外脚本的实际加载。

<head>
  <title>snake</title>
  <script src="../javascripts/p5/p5.js"></script>
  <script src="../javascripts/p5/addons/p5.dom.js"></script>
  <script src="../javascripts/p5/addons/p5.sound.js"></script>

  <script scr=../javascripts/library/colors.js ></script>

  <script src=../javascripts/experiments/snake/sketch.js></script>
  <style> body {padding: 0; margin: 0;} </style>
</head>

colors.js文件没有加载我错过了什么,sketch.js是动态的,它加载得很好。

1 个答案:

答案 0 :(得分:0)

您的代码中存在拼写错误 使用 src 代替 scr

还尝试将src路径括在双引号内,如下所示

<head>
  <title><%= name %></title>
  <script src="../javascripts/p5/p5.js"></script>
  <script src="../javascripts/p5/addons/p5.dom.js"></script>
  <script src="../javascripts/p5/addons/p5.sound.js"></script>
  <% for(var i = 0; i < extraScripts.length; i++) { %>
    <script src="<%= "../javascripts/" + extraScripts[i]%>" ></script>
  <% }%>
  <script src="<%= "../javascripts/experiments/"+name + "/sketch.js"%>"></script>
  <style> body {padding: 0; margin: 0;} </style>
</head>