简体   繁体   中英

Does DOMContentLoaded wait for web fonts (Firefox)?

I'm using Google's web fonts in an application and I noticed that DOMContentLoaded doesn't seem to fire in Firefox until after the web font is downloaded. Am I doing something wrong or is this expected behavior?

My font is included with something like this placed in the head section:

<link href="http://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet">

My JavaScript is linked at the bottom of my page with an event added like this:

document.addEventListener('DOMContentLoaded', function() {
  ...do stuff...
})

I tried testing this on Chrome but couldn't really determine which order it happened (the font loaded so fast).

According to Mozilla's documentation on DOMContentLoaded :

Note: Stylesheet loads block script execution, so if you have a <script> after a <link rel="stylesheet" ...> , the page will not finish parsing - and DOMContentLoaded will not fire - until the stylesheet is loaded.

Thus, it appears that you are experiencing the expected behavior such that DOMContentLoaded is not fired until after your external web font is fully downloaded.

NO, it does NOT!

tested in Chrome and Firefox. which is a silly thing, as custom fonts may change dimensions of the layout, so you have to apply some tricks.. to make it pixel perfect.

The simpliest way to bypass this (initialization pitfails with size/position detection, like getBoundingClientRect() etc.) with modern browsers is to do:

window.addEventListener('load', /* do things here */)

..or, another way is to put, for example:

<link rel="preload" href="fonts/Oxygen.woff2" as="font">

inside the head (it's called browser preload hints).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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