如何从PHP文件输出可从脚本include标记引用的javascript文件 [英] How to output a javascript file from a PHP file that can be referenced from a script include tag
问题描述
我正在寻找一种PHP解决方案,该解决方案将允许我引用一个PHP文件,该文件输出javascript,因为该脚本包含在html页面的标题中.我要执行此操作的原因是因为我有一些动态生成的JavaScript,希望浏览器进行缓存.
I am looking for a solution in PHP that will allow me to reference a PHP file that outputs javascript as a script includes in the header of my html page. The reason i'm looking to do this is because I have some dynamically generated javascript which I want the browser to cache.
我以前在ASP.NET中通过使用.ashx处理程序来完成此操作,但是我不确定如何在PHP中执行此操作.
I have done this before in ASP.NET by using a .ashx handler, but i'm not sure how to do it in PHP.
这是我要实现的目标的更详细细分.
Here's a more detailed breakdown of what i'm trying to achieve.
<!DOCTYPE html>
<html lang="en">
<script type="text/javascript" src="javascriptHandler.php"></script>
<head>
</head>
在上面的示例中,我希望 javascriptHandler.php
在请求后以一个javascript文件响应. javascriptHandler.php
需要检查传入的请求标头,并确定文件在客户端上是否已存在并返回适当的响应.
In the above example I want the javascriptHandler.php
to respond with a javascript file once it's requested.
The javascriptHandler.php
needs to check the incoming request headers and determine whether the file already exists on the client and return the appropriate response.
我正在寻找可以完成上述操作的任何干净解决方案,或者正在寻找可以为我指明正确方向的任何链接.如果有更好的方法来包含和缓存动态生成的javascript,请在此处发布.
I'm looking for any clean solution that will do what is described above or any links that will point me in the right direction. If there's a better way to include and cache dynamically generated javascript please post it here.
推荐答案
将JavaScript标头放入PHP文件
使您的HTML页面保持不变.称为 .php
文件:
<script type="text/javascript" src="javascriptHandler.php"></script>
在您的 javascriptHandler.php
文件中,将此文件添加到文件的顶部:
In your javascriptHandler.php
file, add this to the very top of the file:
<?php
header("Content-Type: application/javascript");
header("Cache-Control: max-age=604800, public");
?>
然后,您可以在下面放置常规的javascript.总共看起来像这样:
Then you can put your regular javascript below. All together it will look like:
<?php
header("Content-Type: application/javascript");
header("Cache-Control: max-age=604800, public");
?>
function bob(){
alert('hello')
}
bob();
,您的浏览器会将您的 javascriptHandler.php
文件视为JavaScript资源.普通的缓存规则将适用.
and your browser will treat your javascriptHandler.php
file like a JavaScript resource. Normal caching rules will apply.
这篇关于如何从PHP文件输出可从脚本include标记引用的javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!