forked from morris/typekit-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypekit-cache.js
68 lines (43 loc) · 1.69 KB
/
typekit-cache.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
( function ( document, proto, method, storage, key, domain, /* min */ cached, style, setAttribute ) {
// If CSS is in cache, append it to <head> in a <style> tag.
cached = storage[ key ];
if ( cached ) {
style = document.createElement( 'style' );
style.innerHTML = cached;
document.getElementsByTagName( 'head' )[ 0 ].appendChild( style );
document.documentElement.className += ' wf-cached';
}
// The typekit will at some point create a <link> to load its CSS.
// Override Element.prototype.setAttribute to handle setting its href.
setAttribute = proto[ method ];
proto[ method ] = function ( name, url, /* min */ xhr, css ) {
if ( typeof url == 'string' && url.indexOf( domain ) > -1 ) {
try {
// Get the CSS of the URL via XHR and cache it.
// Only overwrite cache if CSS has changed.
xhr = new XMLHttpRequest();
xhr.open( 'GET', url, true );
xhr.onreadystatechange = function () {
try {
if ( xhr.readyState == 4 ) {
// Make relative URLs absolute. Fixes #2
css = xhr.responseText.replace( /url\(\//g, 'url(' + domain + '/' );
// Store new CSS if modified.
if ( css !== cached ) storage[ key ] = css;
}
} catch ( x ) {
// Fall back to regular behavior. Fixes #3
if ( style ) style.innerHTML = '';
}
};
xhr.send( null );
} catch ( x ) {
// The only possible side effect here is an empty <style> element.
}
// Reset Element.prototype.setAttribute
proto[ method ] = setAttribute;
}
// Always apply original setAttribute
return setAttribute.apply( this, arguments );
};
} )( document, Element.prototype, 'setAttribute', localStorage, 'tk', 'https://use.typekit.net' );