javascript - node.js express rendering inside included js files - Stack Overflow

Lets say I have a simple view<html><head><title>something<title><head>&

Lets say I have a simple view

<html>
  <head>
    <title>something</title>
  </head>
  <body>
  <%= param %>
  </body>
  <script type="text/javascript" src="myscript.js"></script>
</html>

And here's myscript.js

$(function() {
  var p = <%= param %>
}

Can I make express rendering engine (in this case ejs) render inside myscript.js ?

Lets say I have a simple view

<html>
  <head>
    <title>something</title>
  </head>
  <body>
  <%= param %>
  </body>
  <script type="text/javascript" src="myscript.js"></script>
</html>

And here's myscript.js

$(function() {
  var p = <%= param %>
}

Can I make express rendering engine (in this case ejs) render inside myscript.js ?

Share Improve this question edited Oct 30, 2013 at 15:54 Michael asked Oct 30, 2013 at 15:33 MichaelMichael 23k35 gold badges136 silver badges189 bronze badges 4
  • Any reason you can't use static javascript files and dynamic JSON? – giaour Commented Oct 30, 2013 at 15:45
  • @giaour can you elaborate on this a little ? – Michael Commented Oct 30, 2013 at 15:55
  • 1 Not passing your JavaScript through the rendering engine will speed up your page, both because view rendering consumes resources and because browsers aggressively cache static files. If the only thing that changes in your javascript files is the value of param, then you can feed it into your page in other ways -- either by having your script make AJAX requests that get handled by Express or by interpolating them into an inline script tag on whatever page uses your script. – giaour Commented Oct 30, 2013 at 16:52
  • thanks for that, makes sense. Although I wouldn't go as far as making an AJAX call, it has i/o overhead as well probably bigger than the rendering but you're probably right about making the script inline... – Michael Commented Oct 30, 2013 at 20:28
Add a ment  | 

1 Answer 1

Reset to default 4

I don't believe express will touch your static files. You could make this a view that gets rendered and served from a route, as in:

app.get('/js/myscript.js', function(req, res) { 
    res.render('myscript'); 
});

With regex routes, you could do this with anything ending in .js. (Before anyone downvotes, note that I said could, not should.)

You probably would be better off with static javascript being served to the browser that uses JSON data served from Express, though.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745393447a4625770.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信