简体   繁体   English

仅链接正在使用的组件的样式表

[英]Only link stylesheets for components in use

I am building a page with PHP and am making heavy use of templating to split the various parts of each page up into reusable components, each of which has its own stylesheet which is automatically added to the head by script. 我正在使用PHP构建页面,并大量使用模板将每个页面的各个部分拆分为可重用的组件,每个组件都有自己的样式表,这些样式表会自动通过脚本添加到头部。

However, to save bandwidth and avoid style conflicts in certain situations, I would like to only link those stylesheets which are actually used on a given page. 但是,为了节省带宽并避免在某些情况下的样式冲突,我只想链接那些在给定页面上实际使用的样式表。 Since the head goes first in the page and the styles go in the head, but there's no way to access something like get_included_files() until the end of the page, I'd (presumably) need a way to reach back into the head and add the link tags later, but I'm not sure how to do that. 由于头部在页面中排在首位,样式在头部中,但是直到页面末尾都无法访问类似get_included_files()类的东西,我(大概)需要一种方法来回到头部并稍后添加链接标签,但是我不确定该怎么做。

The only obvious way I can think of is to necessitate a registry array of all the components which will be used, and then use that to generate the link tags, but that is not really viable because some of the components include other components, so it would be necessary to manually register not just the components included in the top-level file, but all the components included by those components as well. 我能想到的唯一显而易见的方法是必要要使用的所有组件的一个数组,然后用它来生成链接的标签,但是这是不是真的可行,因为一些组件包括其他部件,所以它不仅需要手动注册顶级文件中包括的组件,还需要手动注册这些组件包括的所有组件。

I figured out a solution. 我想出了一个解决方案。 I took each of my components, and basically wrapped them in a class and a public static function of that class, called output() . 我采用了每个组件,基本上将它们包装在一个类和该类的一个公共静态函数中,该函数称为output() I can now include() all the components I want to use right at the start, and then just do Component::output() wherever I want it to appear. 现在,我可以一开始就include()我要使用的所有组件,然后只要在要显示它的位置执行Component::output()即可。 This way, all the files are included, and visible to get_included_files() , by the time I call output() on the script that generates the head. 这样,当我在生成头文件的脚本中调用output()时,所有文件都被包含在内,并且对get_included_files()可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM