简体   繁体   中英

Minify Inline-JavaScript with PHP

Currently for my site, I'm able to minify JavaScript and CSS code through linked <link> and <script> tags.

Example:

<script src="/inc/php/jsmin.php?f=inc/js/core.js"></script>

But, to reduce HTTP requests, I have inline scripts and styles as well. I also have inline scripts and styles because I don't need everything included on every page I make.

Is there a way I can use PHP DOM or something else to minify code on the same file that the script is running on?

You could do doing something like this:

<?php require '/inc/php/jsmin.php'; ?>

// your regular html here

<?php echo JSMin::minify(file_get_contents('js/page-name/your-old-inline.js')); ?>

// your regular html here

The approach I would take is to take the inline JS and move it into separate files then use jsmin.php to minify the file. This reduces the HTTP requests and the overhead of file_get_contents() is relatively small.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM