admin管理员组

文章数量:1426481

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.

本文标签: javascriptnodejs express rendering inside included js filesStack Overflow