@@ -39,7 +39,7 @@ const getAbsoluteUrl = (resolveDir, url) => {
39
39
* @param {string } digest
40
40
* @returns {string }
41
41
*/
42
- const buildInjectCode = ( injectToSelector = 'head' , css , digest , { urlFullPathMap } ) => {
42
+ const buildInjectCode = ( injectToSelector = 'head' , css , digest , { urlFullPathMap, injectEvent } ) => {
43
43
const patchedPlaceholders = [ ] ;
44
44
const imports = Object . keys ( urlFullPathMap )
45
45
. map ( ( placeholder ) => {
@@ -50,6 +50,7 @@ const buildInjectCode = (injectToSelector = 'head', css, digest, { urlFullPathMa
50
50
. join ( '\n' ) ;
51
51
return `${ imports }
52
52
(function(){
53
+ const injectEvent = ${ injectEvent ? `"${ injectEvent } "` : 'undefined' }
53
54
let css = \`${ css } \`;
54
55
${
55
56
patchedPlaceholders . length
@@ -65,22 +66,31 @@ const buildInjectCode = (injectToSelector = 'head', css, digest, { urlFullPathMa
65
66
}
66
67
67
68
const __inject = function() {
68
- let root = document.querySelector('${ injectToSelector } ');
69
- if (root && root.shadowRoot) {
70
- root = root.shadowRoot;
69
+ const doInject = () => {
70
+ let root = document.querySelector('${ injectToSelector } ');
71
+ if (root && root.shadowRoot) {
72
+ root = root.shadowRoot;
73
+ }
74
+ if (!root) {
75
+ root = document.head;
76
+ console.warn('[esbuild-css-modules-plugin]', 'can not find element \`${ injectToSelector } \`, append style to', root);
77
+ }
78
+ if (!root.querySelector('#_${ digest } ')) {
79
+ const el = document.createElement('style');
80
+ el.id = '_${ digest } ';
81
+ el.textContent = css;
82
+ root.appendChild(el);
83
+ }
71
84
}
72
- if (!root) {
73
- root = document.head;
74
- console.warn('[esbuild-css-modules-plugin]', 'can not find element \`${ injectToSelector } \`, append style to', root);
75
- }
76
- if (!root.querySelector('#_${ digest } ')) {
77
- const el = document.createElement('style');
78
- el.id = '_${ digest } ';
79
- el.textContent = css;
80
- root.appendChild(el);
85
+ if (injectEvent) {
86
+ window.addEventListener(injectEvent, function() {
87
+ doInject();
88
+ });
89
+ } else {
90
+ doInject();
81
91
}
82
92
}
83
- if (document.readyState !== 'interactive' && document.readyState !== 'complete') {
93
+ if (!injectEvent && document.readyState !== 'interactive' && document.readyState !== 'complete') {
84
94
window.addEventListener('DOMContentLoaded', function() {
85
95
__inject();
86
96
});
0 commit comments