将css置于头部但css是导入文件的一部分

时间:2013-05-18 21:40:32

标签: php html css

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>

我能为此做点什么吗?

1 个答案:

答案 0 :(得分:0)

我想这可能会告诉你,你的视图需要一个不错的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();
?>