开发者

How can I handle javascript and css includes across multiple pages so they are easy to manage?

开发者 https://www.devze.com 2023-01-26 18:48 出处:网络
I am working on revamping 开发者_开发百科an older CMS and I am wondering how I should handle things like multiple css and javascript files that only need to be included on certain pages.

I am working on revamping 开发者_开发百科an older CMS and I am wondering how I should handle things like multiple css and javascript files that only need to be included on certain pages.

Let's say for example I have the following pages:

  • services.php -> requires jquery-1.4.2.min.js
  • index.php -> no javascript required

However, on each of these pages, I am including a file from an includes folder

include 'includes/inc_header.php';

This file contains code like the following:

<!doctype ...>
<html>
<head>
<script type="text/javascript">...

Here is where I run into the problem. I have thought about using an array and looping through and printing each element required. This way each page could simply add the scripts they need to the array. I thought this might get very complicated very fast however.

Can anyone give me a good approach to solving this problem?


Well depending on how much work you wanna do i would reverse the view processing and move to a Front Controller that uses a 2-step view. This way your outer layout with the overall structure (doctype, head, etc.) is rendered last, allowing you to modify the output for this outer layout form within the inner layout.

While this will require potentially intensive restructuring it will give you a lot more flexibility in what you can do. Then again this probably going to be a lot of work so you would have to decide whether it is worth the investment.


You could reverse your logic on your array script idea

Inside your header output files conditionally depending on a flag

eg. (psuedocode)

array core (scripts and css for all pages) array index (particular index scripts) array page1 (etc)

then

if page1 merge_array core+page1 loop through and output

So your header has all the permutations but is context aware - maybe through a php variable on each page or by passing a variable to the include or reading some url parameter so only loads those required

0

精彩评论

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