I want to put snippets like these inside of a few php files and then require them in my main page, instead of using “pure” css and js files. I mean, I already do essentially this for my HTML DOM.
this:
<script type='text/javascript'>
var foo = <?php echo $bar; ?>;
</script>
or this:
<style type='text/css'>
.foo{
background-image:url('<?php echo $bar; ?>image.png');
}
</style>
is that really bad practice?
and, if it is, what are the pros and cons of such an approach?
Update:
These days I’m just using Drupal which handles passing PHP variables to js in the theme system and supports CSS preprocessors like LESS and SASS. Both of the use cases I’ve raised in this question are handled pretty well by modern frameworks/preprocessors.
Although CSS is not a problem, you’d have trouble if you wanted to send this as an HTTP response via AJAX.
AJAX won’t allow Javascript for security reasons.
Best practice is to keep your Javascript in a separate file. That way client-side caching of the script will be to your advantage in terms of traffic too.