IE11和Microsoft Edge 40中不会触发以下onload事件:
<link href="https://fonts.googleapis.com/css?family=Montserrat:300" rel="preload" as="style" onload="this.rel = 'stylesheet';">
如果你给onload
元素一个有效的<link>
,rel="stylesheet"
会触发:
<link href="https://fonts.googleapis.com/css?family=Montserrat:300" rel="stylesheet" onload="alert('this works')">
什么是rel="preload"
在Internet Explorer / Edge上的后备解决方案?
经过一番挖掘后,我发现了一个可以检测来自rel="preload"
的Yoav Weiss's article的解决方案:
var DOMTokenListSupports = function(tokenList, token) {
if (!tokenList || !tokenList.supports) {
return;
}
try {
return tokenList.supports(token);
} catch (e) {
if (e instanceof TypeError) {
console.log("The DOMTokenList doesn't have a supported tokens list");
} else {
console.error("That shouldn't have happened");
}
}
};
var linkSupportsPreload = DOMTokenListSupports(document.createElement("link").relList, "preload");
if (!linkSupportsPreload) {
// Dynamically load the things that relied on preload.
}
onload="this.rel='stylesheet'"
,如果它在IE / Edge中工作,那将是一个很好的后备。 Scott Jehl's loadCSS library has its own polyfill for rel = preload。
所以我正在利用该解决方案的一部分将rel=preload
更新为rel=stylesheet
。
我的最终解决方案
// `rel=preload` Polyfill for <link> elements
var DOMTokenListSupports = function (tokenList, token) {
if (!tokenList || !tokenList.supports) {
return;
}
try {
return tokenList.supports(token);
}
catch (e) {
if (e instanceof TypeError) {
console.log("The DOMTokenList doesn't have a supported tokens list");
}
else {
console.error("That shouldn't have happened");
}
}
};
var linkSupportsPreload = DOMTokenListSupports(document.createElement('link').relList, 'preload');
if (!linkSupportsPreload) {
// Dynamically load the things that relied on preload.
var links = document.getElementsByTagName('link');
for (var i = 0; i < links.length; i++) {
var link = links[i];
// qualify links to those with rel=preload and as=style attrs
if (link.rel === 'preload' && link.getAttribute('as') === 'style') {
// prevent re-running on link
link.setAttribute('rel', 'stylesheet');
}
}
}