1

在我网站的主页上,我想预加载网站其他页面上使用的字体和图像,以避免 FOUC。

最好的方法是什么?

对于字体,我目前在我的主页上有此代码,但我确信有更好的方法。

<div id="font-load1">aaa</div>
<div id="font-load2">aaa</div>

然后在 style.css 中隐藏文本:

#font-load1{
    font-family:"BellMTItalic";
    font-style:italic;
    text-indent: -900%;

}
#font-load2{
    font-family:"SavoyeLETPlain";
    text-indent: -900%;
}

谢谢

4

4 回答 4

2

不需要外部库的最简单方法是将预加载元素放在一个 div 设置为display: none.

于 2011-10-12T19:37:19.940 回答
0

如果您需要预加载某些内容,则应在页面加载后将其动态添加到页面上的隐藏元素中。然后,您根本不会减慢用户的速度,因为您不想用完分配给您网页的可用连接。

如果您关心非 JavaScript 用户,我会将隐藏元素放在页面上的最后一件事。假设浏览器继续以自上而下的方式加载样式,这不会减慢页面的其余部分。

对于图像,您可能想尝试 spritesheets。它们可能在您的用例中运行良好。

您还可以查看其他内容,例如文件的压缩和缓存设置。

一旦您认为您已经找到了解决方案,请加载 Fiddler 并验证该站点是否按您预期的方式运行。

于 2011-10-12T19:44:52.140 回答
0

好消息;有一个规范和方法可以声明式地做到这一点:

<link rel="preload" href="/path/to/font/BellMTItalic.woff2" as="font" type="font/woff2">
<link rel="preload" href="/path/to/font/SavoyeLETPlain.woff2" as="font" type="font/woff2">

https://w3c.github.io/preload/

http://www.bramstein.com/writing/preload-hints-for-web-fonts.html


坏消息:

仅受 Chrome 和 Opera 支持(2016 年 10 月):

http://caniuse.com/#search=preload


正如@brad 所提到的,您需要在主页上具有极低的跳出率才能做到这一点。

于 2016-10-08T20:01:05.227 回答
-1

对于您的图像:

JavaScript

function preload() {
    imageObj = new Image();
    images = new Array();
    images[0] = 'img/1.png';
    images[1] = 'img/2.png';
    images[2] = 'img/3.png';
    images[3] = 'img/4.png';
    images[4] = 'img/5.png';

    for (i = 0; i <= 4; i++)
        imageObj.src = images[i];
}

HTML

<body onload="preload();">
    ....

    <!--[if IE]>
        <div id="preload">
            <img src="img/1.png" width="1" height="1" alt="" />
            <img src="img/2.png" width="1" height="1" alt="" />
            <img src="img/3.png" width="1" height="1" alt="" />
            <img src="img/4.png" width="1" height="1" alt="" />
            <img src="img/5.png" width="1" height="1" alt="" />
        </div>
    <![endif]-->
</body>

用于 IE 的 CSS

#preload {
   position: absolute;
   overflow: hidden;
   left: -9999px; 
   top: -9999px;
   height: 1px;
   width: 1px;
}

当然,您可以以相同的方式预加载字体。

于 2011-10-12T19:47:23.953 回答