Unglify / minify embedded scripts
SDPrio opened this issue · 3 comments
Compressing linked JavaScript and CSS files is no big deal when using Assetic in my Symfony 2.8 project. But what about scripts that are directly embedded in the page/template using a script tag.
Is it possible to compress/modify/uglify these scripts as well using the existing Assetic features (e.g. the Twig extension)?
Of course I could simply move these scripts into separate files and thus apply the Assetic filters to them as well. But in some cases it is just handy to have the scripts directly within the HTML / Twig template.
Assetic currently does not provide a feature to compress/uglify inline scripts, no.
There are 2 different cases here:
- having inline scripts which don't contain any Twig syntax inside them => these could safely be minified at compile-time
- having inline scripts using Twig features inside them => these cannot be minified at compile time, as the JS code is not available yet at that time.
In the second case, I suspect that the overhead of running Assetic would far outweight the benefit of downloading a smaller code (mangling is not meant to be done on the fly by any tool I know of, and even less when using a PHP script to call a subprocess doing this work with UglifyJS).
For the first case, this could be solved. But I'm wondering whether it is useful in this case, compared to minifying an external file (and maybe using {{ include(['inline.min.js', 'inline.js']) }}
in Twig if you want to embed it inline, with a fallback to the non-minified file if the minified one was not generated)
Well, would it be possible to use Assetics UglifyJs2Filter
manually in my own Twig extension? The idea would be:
- Create custom
Twig
extension to add auglify
tag, that could be used to wrap scripts:
<script type="text/javascript">
// no changes here...
</script>
{% unglify %}
<script type="text/javascript">
// minify, uglify, compress
</script>
{% end_unglify %}
- Use the
Twig
extension to get/handle the content of the tag - Use Assetics
UglifyJs2Filter
to uglify/minify the content/script - Return the uglified content to build the page...
yes it would be possible to use it (Assetic itself is not a Twig extension. It has a Twig extension to make things easier).
However, as I said above, you have to be careful about the use case. Uglifying at render time is likely to make your performance worse.