Skip to content
This repository was archived by the owner on Oct 21, 2022. It is now read-only.

Commit d823c63

Browse files
committed
modify the way the media toggle callback is handled so that the link contexts are enclosed correctly. fixes #250
1 parent 711a580 commit d823c63

1 file changed

Lines changed: 19 additions & 13 deletions

File tree

src/cssrelpreload.js

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,22 @@
2121
}
2222
};
2323

24+
// if preload isn't supported, get an asynchronous load by using a non-matching media attribute
25+
// then change that media back to its intended value on load
26+
rp.bindMediaToggle = function( link, media ){
27+
function enableStylesheet(){
28+
link.media = media;
29+
}
30+
if( link.addEventListener ){
31+
link.addEventListener( "load", enableStylesheet );
32+
} else if( link.attachEvent ){
33+
link.attachEvent( "onload", enableStylesheet );
34+
}
35+
// also enable media after 3 seconds,
36+
// which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
37+
setTimeout( enableStylesheet, 3000 );
38+
};
39+
2440
// loop through link elements in DOM
2541
rp.poly = function(){
2642
if( rp.support() ){
@@ -33,22 +49,12 @@
3349
if( link.rel === "preload" && link.getAttribute( "as" ) === "style" && !link.getAttribute( "data-loadcss" ) ){
3450
// remember existing media attr for ultimate state, or default to 'all'
3551
var finalMedia = link.media || "all";
36-
// if preload isn't supported, get an asynchronous load by using a non-matching media attribute
37-
// then change that media back to its intended value on load
38-
var enableStylesheet = function(){
39-
link.media = finalMedia;
40-
}
41-
if( link.addEventListener ){
42-
link.addEventListener( "load", enableStylesheet );
43-
} else if( link.attachEvent ){
44-
link.attachEvent( "onload", enableStylesheet );
45-
}
52+
// bind listeners to toggle media back
53+
rp.bindMediaToggle( link, finalMedia );
4654
// if preload is not supported, kick off an asynchronous request by using a non-matching media query and rel=stylesheet
4755
link.media = "x";
4856
link.rel = "stylesheet";
49-
// set rel=preload to stylesheet after 3 seconds,
50-
// which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
51-
setTimeout( enableStylesheet, 3000 );
57+
5258
// prevent rerunning on link
5359
link.setAttribute( "data-loadcss", true );
5460
}

0 commit comments

Comments
 (0)