评估 php 生成的 javascript “内联”?
如果您查看此页面的来源 http://kingston.talking-newspapers.co.uk/ 你会在顶部附近看到大量的内联 JavaScript。
我真的不希望所有这些额外的东西在我的页面源代码中漂浮,我宁愿将其放入脚本标记中,然后我可以缩小它和各种。
如果我将其称为 php 文件,理论上这应该有效,我只是以 php 结尾 js 文件扩展名,并在标头中添加以下内容:
header("Content-type:application/x-javascript");
但是...很多用于生成播放列表的 php 变量javascript 中的内容设置在主 index.php 文件的开头,并且在像这样调用这个 php 生成的 js 播放列表文件时,它似乎完全单独评估它,因此它充满了错误。
我能想到的唯一方法是让页面写入一个文件,然后立即读入它。另一件事是,播放列表可能会经常动态地更改,所以我认为我需要缩小以不缓存它?
If you look at the source of this page http://kingston.talking-newspapers.co.uk/ you will see a large amount of inline javascript near the top.
I don't really want all this extra stuff floating around in my page source, I'd much rather get it off into a script tag, and then I can minify it and all sorts.
If I call it as a php file, this SHOULD work in theory, I just end the js file extension with php instead, and in the header I put the following:
header("Content-type:application/x-javascript");
but... a lot of the php variables used to generate the playlist within the javascript are setup at the beginning of the main index.php file, and in calling this php-generated js playlist file like this, it seems to evaluate it entirely separately, so it's full of errors.
The only way round it I can think of is to have the page write a file, then immediately read it in. The other thing is, the playlist is likely to change often and dynamically, so I think I need to get minify to NOT cache it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我按照本教程提出了解决方案,它将生成内联脚本重定向到文件,然后立即读取该文件。
http://my.opera.com/zomg/blog/2007/10/03/how-to- easy-redirect-php-output-to-a-file
所以现在我的页面看起来像:
瞧瞧!一切都很好地外部化,可以缩小、缓存等。
I made the solution by following this tutorial, which redirects the generate inline script to a file, then immediately reads that file in.
http://my.opera.com/zomg/blog/2007/10/03/how-to-easily-redirect-php-output-to-a-file
So now my page looks like:
<script type="text/javascript" src="jplay_gen_playlist.js"></script>
et voila! All nicely external, can be minified, cached etc.
您可以通过两种方式做到这一点。首先将设置内联变量,然后包含脚本:
另一种方法是让包含的 .js 文件包含一个简单的函数库,将其包含在页面顶部,然后调用一些内联javascript:
我个人会选择第二种方法。您不需要动态生成任何脚本(据我所知,除了播放列表之外,它都可以被硬编码,对吧?)您需要传递给脚本的任何其他内容仍然可以传递无论如何,通过您的
startPlaylist()
方法调用。You can do it in two ways. First would be set up the variable inline and then include the script:
The other would be to have your included .js file a simple library of functions which you include at the top of the page and then call from some inline javascript:
I would personally choose the second method. You shouldn't need to generate any of the script dynamically (as far as I can see, it can all be hard-coded except for the playlist, right?) Any other things you need to pass to the script could still be passed in by your
startPlaylist()
method call anyway.