预加载字体和图像?
在我网站的主页上,我想预加载网站其他页面上使用的字体和图像,以避免 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%;
}
谢谢
On the home page of my site I'd like to preload fonts and images that are used on other pages of the site, to avoid FOUC's.
What's the best way to do this?
For fonts I currently have this code on my homepage but I'm sure there's a better way.
<div id="font-load1">aaa</div>
<div id="font-load2">aaa</div>
And then in style.css to hide the text:
#font-load1{
font-family:"BellMTItalic";
font-style:italic;
text-indent: -900%;
}
#font-load2{
font-family:"SavoyeLETPlain";
text-indent: -900%;
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的方法(不需要外部库)是将预加载元素放置在设置为
display: none
的 div 中。The simplest method, requiring no external libraries, is to place your preload elements in a div set to
display: none
.如果您需要预加载某些内容,则应该在页面加载后将其动态添加到页面上的隐藏元素中。这样您就不会减慢用户的速度,因为您不想用完分配给您的网页的可用连接。
如果您关心非 JavaScript 用户,我会将隐藏元素放置在页面的最后。假设浏览器继续以自上而下的方式加载样式,这不会减慢页面的其余部分。
对于图像,您可能想尝试 spritesheet。它们可能在您的用例中运行良好。
您还可以查看其他内容,例如文件的压缩和缓存设置。
一旦您认为您已经找到了解决方案,请加载 Fiddler 并验证该站点是否按您的预期运行。
If you need to preload something, you should dynamically add it to a hidden element on the page after page load. Then you will not slow down the user at all as you do not want to use up the available connections alloted to your webpage.
If you care about non-JavaScript users, I would place the hidden elements as the last thing on the page. Assuming browsers continue to load the styles in a top-down matter this will not slow down the rest of the page.
For images, you may want to try spritesheets. They may work well in your use case.
There are other things that you can look at too like compression and caching settings of your files.
Once you think you have your solution figured out, load up Fiddler and verify that the site is performing as you expected.
好消息;
有一个规范和方法可以以声明方式执行此操作:
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 提到的,你需要使您的主页具有极低的跳出率,以良心做到这一点。
The good news;
There's a spec and way to do it declaratively:
https://w3c.github.io/preload/
http://www.bramstein.com/writing/preload-hints-for-web-fonts.html
The Bad news:
Only supported by Chrome and Opera (Oct 2016):
http://caniuse.com/#search=preload
And as @brad mentioned, you'd need to have an extremely low bouncerate on your homepage to do this with a good conscience.
对于您的图像:
JavaScript
HTML
CSS for IE
当然,您可以以相同的方式预加载字体。
For your images :
JavaScript
HTML
CSS for IE
Surely you can preload the fonts in the same way.