清理指向 PHP 生成的 JavaScript 和 CSS 的链接

2022-01-04 00:00:00 templates php javascript css scripting

背景:当用 PHP 或任何类似的东西生成 HTML 内容时,可以将 JavaScript 和 CSS 的链接封装在标签内,而无需实际包含 CSS 和 JavaScript内嵌"其余的内容.您所要做的就是创建指向该文件的链接.

Background: When generating HTML content with PHP or any such thing, it is possible to encapsulate links to JavaScript and CSS inside tags without actually having to include the CSS and JavaScript "in-line" with the rest of the content. All you have to do is create a link to the file.

示例:{script type="text/javascript" src="./js/fooscript.js"}{/script}

Example: {script type="text/javascript" src="./js/fooscript.js"}{/script}

问题: 但是,如果您的 PHP 需要动态生成部分或全部 JavaScript 代码,则上述方法不起作用.有没有办法像上面那样有一个干净的单行"链接,但仍然使用动态生成的 JavaScript?

Question: The above approach does not work, however, if your PHP needs to dynamically generate some or all of your JavaScript code. Is there a way to have a clean "one-line" link as above, but still use dynamically-generated JavaScript?

显然,一种方法是让 PHP 自动生成 JavaScript 并将其写入文件;然而,由于各种原因,这种方法是不可取的.我想知道是否有我还没有想到的替代技巧来做到这一点.

Obviously, one way to do it is to have PHP auto-generate the JavaScript and write that to a file; however that approach is undesirable for various reasons. I am wondering if there is an alternate trick to doing this that I have not thought of yet.

推荐答案

在你的 /js/ 文件夹中放入一个 .htaccess 文件并添加 .js 对 PHP 的扩展,像这样:

Put an .htaccess file in your /js/ folder and add the .js extension to PHP, like this:

AddHandler application/x-httpd-php .js

换句话说,让 PHP 将所有 .js 文件解析为 PHP 文件.因此,您的脚本实际上是服务器端输出 JavaScript 的 PHP 文件.对样式表做同样的事情,显然只使用 .css 扩展名.

In other words, have PHP parse all .js files as PHP files. So your scripts would really be PHP files on the server-side that output JavaScript. Do the same for stylesheets, only use the .css extension, obviously.

注意:我从未尝试过在单独的 .htaccess 文件中执行此操作.如果它不起作用,只需将其放入您的全局 Apache 配置中.

Note: I've never tried doing this in a separate .htaccess file. If it doesn't work, just put it into your global Apache config.

相关文章