-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathload-css.js
79 lines (76 loc) · 2.31 KB
/
load-css.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
69
70
71
72
73
74
75
76
77
78
79
define([], function(){
'use strict';
// this module is responsible for doing the loading/insertion
// of stylesheets to get CSS loaded.
var cache = typeof _css_cache == 'undefined' ? {} : _css_cache;
var doc = document;
function has(){
return !doc.createStyleSheet;
}
var head = doc.head;
function insertCss(css){
if(has("dom-create-style-element")){
// we can use standard <style> element creation
styleSheet = doc.createElement("style");
styleSheet.setAttribute("type", "text/css");
styleSheet.appendChild(doc.createTextNode(css));
head.appendChild(styleSheet);
return styleSheet;
}
else{
// IE's stylesheet insertion
var styleSheet = doc.createStyleSheet();
styleSheet.cssText = css;
return styleSheet.owningElement;
}
}
function load(resourceDef, callback, options){
var cached = cache[resourceDef];
if(cached){
// if it is cached (from a build), we directly insert
link = insertCss(cached);
return callback(link);
}
// create a link element to load the stylesheet
var link = doc.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = resourceDef;
var wait = !options || options.wait !== false;
// old webkit's would claim to have onload, but didn't really support it
var webkitVersion = navigator.userAgent.match(/AppleWebKit\/(\d+\.?\d*)/);
webkitVersion = webkitVersion && +webkitVersion[1];
if(link.onload === null && !(webkitVersion < 536)){
// most browsers support this onload function now
link.onload = function(){
// cleanup
link.onload = null;
link.onerror = null;
wait && callback(link);
};
// always add the error handler, so we can notify of any errors
link.onerror = function(){
// there isn't really any recourse in AMD for errors, so
// we just output the error and continue on
console.error('Error loading stylesheet ' + resourceDef);
wait && callback(link);
};
}else if(wait){
var interval = setInterval(function(){
if(link.style){
// loaded
clearInterval(interval);
callback(link);
}
}, 15);
}
// add it to the head to trigger loading
(head || doc.getElementsByTagName('head')[0]).appendChild(link);
if(!wait){
// don't wait for the stylesheet to load, proceed
callback(link);
}
}
load.insertCss = insertCss;
return load;
});