fom*_*icz 5 javascript css php content-type
像其他人一样,我将我的网站显示信息存储在样式表文件中.我想创建后端cms,以便用户能够,例如,更改<h1>颜色,大小等.
那么,在我的CSS文件中嵌入PHP代码的正确方法是什么?
是添加此标头:
<?php header("Content-type: text/css"); ?>
Run Code Online (Sandbox Code Playgroud)
并在链接中更改文件扩展名:
<link rel="stylesheet" type="text/css" media="screen" href="style.php">
Run Code Online (Sandbox Code Playgroud)
有效?
那JavaScript呢?此刻我正在回应<script type="text/javascript">标签,但是也许还有一种方法可以将所有内容嵌入.js文件中?
谢谢!
是的,这是完全有效的.
通过发送也可以为Javascript做同样的事情
<?php header("Content-type: application/javascript"); ?>
Run Code Online (Sandbox Code Playgroud)
但是,从性能的角度来看,这不是最佳选择,因为必须启动PHP进程才能提供这些资源.
如果您只有很少的动态更改CSS属性或JS变量,我会考虑将它们放入文档的头部并继续静态地提供外部文件.
请记住,通常,没有为PHP文件发送缓存标头.您必须注意在PHP脚本中发送正确的标头!干杯@oracle认证专业提醒.
你正在做的是绝对有效的.
但是,如果您正在运行一个包含许多访问者的更大的站点,那么您应该关注的是,当您的用户更新其设计时,让PHP"构建"一个"真正的"CSS文件,以便将您的服务器性能保存为更需要的东西:
<?php
header("Content-type: text/css");
// Your database magic here to fetch the user-specific designs
// open the cached css
$cachefile = "cachedCSS/mycss.css";
if (file_exists($cachefile)) {
// the page has been cached from an earlier request
// output the contents of the cache file
include($cachefile);
// exit the script, so that the rest isnt executed
exit;
}
$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush();
Run Code Online (Sandbox Code Playgroud)
在这里阅读更多相关信息:http://www.theukwebdesigncompany.com/articles/php-caching.php