开发者

How put scripts into header template?

I saw this guy approach into organizing PHP projects http://net.tutsplus.com/tutorials/php/开发者_开发技巧organize-your-next-php-project-the-right-way/comment-page-1/#comments and i liked it, but since the head.php will be the same to all pages how can i put JS scripts only in the pages that need them?


Well, first off, putting JavaScript in the bottom of a page tends to yield the best results, but, to answer your question: if you have scripts that are only relevant to one page, you could save that script with the same name as that PHP page (obviously with a .js extension instead), and then inject the file name into the script reference. I'd also maybe add a flag so that you only look for a JS file when the flag is true:

<?php
$usesJS = true;
$filename = "somerandomname";

if($usesJS){
     echo( '<script src="/js/' . $filename . '.js"></script>' );
}
?>

This would print out something like <script src="/js/somerandomname.js"></script>

Another option is to create an include file for each page and code your script tags as normal inside the include, and then reference the include. I did something like that for a simple site I did where each page had a different jQuery setup and only one needed a plugin.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜