gpt4 book ai didi

php - 将 css 放入 head 但 css 是导入文件的一部分

转载 作者:行者123 更新时间:2023-11-28 12:54:43 26 4
gpt4 key购买 nike

Webpagetest.org 告诉我

http://mypage.com/howitworks has CSS in the document body:
Link node http://mypage.com/design_header.css should be moved to the document head.

这个 design_header.css 是 header.php 的样式表,在正文中导入,例如

<body>
<?php include 'header_login.php'; ?>
</body>

我能做些什么吗?

最佳答案

我想这可能会告诉您,您的 View 需要一个像样的 PHP 模板系统(Smarty?)。

但是,如果您正在寻找快速解决方案,请尝试利用Output Buffering 来满足您的需求:

<?php
// at the top of your parent page

function move_css_to_head($buffer)
{
// do some DOM manipulation here to achieve your goal
$dom = new DOMDocument;
$dom->loadHTML($buffer);

$head = $dom->getElementsByTagName('head')->item(0);
$body = $dom->getElementsByTagName('body')->item(0);
$css_elms = $body->getElementsByTagName('link');

foreach ($css_elms as $elm)
{
$head->appendChild($elm->cloneNode());
$body->removeChild($elm);
}

return $dom->saveHTML();
}

ob_start('move_css_to_head'); // buffer response output, and call the assigned function upon flushing
?>

<!-- Regular Page Content -->

<?php
// at the bottom of your parent page, flush the buffer
ob_end_flush();
?>

关于php - 将 css 放入 head 但 css 是导入文件的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16629234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com