I have an asp.net website, but I need to pass stuff to javascript to do stuff there. At the moment, I am doing things like this:
<script type="text/javascript">
var userHasMicrositePhoto = '<%=hasMicrositePhoto%>';
</script>
But I’ve been told that putting lots of script tags in like this is bad, and also its annoying to have to keep writing Properties in my code behind.
What is a better way to do this?
This is pretty much the ideal way to go IMO. If you have a lot of stuff like this, try putting it all in one
<script>block. You could also use an array to reduce the code overhead, or have asp.net output a JSON encoded array with all the needed properties in it.Depending on your architecture, you could consider fetching those properties through a separate Ajax request which would make the page body a bit cleaner, but it would be an extra request that can’t be cached, so I would use this only in very extreme cases.
The same applies to embedding a separate
<script src=....>it looks nicer in the generated markup, but needs another request to the server.