Fix css injection order

This commit is contained in:
garronej
2021-10-22 18:10:32 +02:00
parent 1572f1137a
commit 92fb3b7529
3 changed files with 40 additions and 10 deletions

View File

@ -8,7 +8,7 @@ import type { KcLanguageTag } from "../i18n/KcLanguageTag";
import { getBestMatchAmongKcLanguageTag } from "../i18n/KcLanguageTag";
import { getKcLanguageTagLabel } from "../i18n/KcLanguageTag";
import { useCallbackFactory } from "powerhooks/useCallbackFactory";
import { appendHead } from "../tools/appendHead";
import { headInsert } from "../tools/headInsert";
import { join as pathJoin } from "path";
import { useConstCallback } from "powerhooks/useConstCallback";
import type { KcTemplateProps } from "./KcProps";
@ -92,12 +92,15 @@ export const Template = memo((props: TemplateProps) => {
[
...toArr(props.stylesCommon).map(relativePath => pathJoin(url.resourcesCommonPath, relativePath)),
...toArr(props.styles).map(relativePath => pathJoin(url.resourcesPath, relativePath)),
].map(href =>
appendHead({
"type": "css",
href,
}),
),
]
.reverse()
.map(href =>
headInsert({
"type": "css",
href,
"position": "prepend",
}),
),
).then(() => {
if (isUnmounted) {
return;
@ -107,7 +110,7 @@ export const Template = memo((props: TemplateProps) => {
});
toArr(props.scripts).forEach(relativePath =>
appendHead({
headInsert({
"type": "javascript",
"src": pathJoin(url.resourcesPath, relativePath),
}),

View File

@ -0,0 +1,9 @@
if (!HTMLElement.prototype.prepend) {
HTMLElement.prototype.prepend = function (childNode) {
if (typeof childNode === "string") {
throw new Error("Error with HTMLElement.prototype.appendFirst polyfill");
}
this.insertBefore(childNode, this.firstChild);
};
}

View File

@ -1,10 +1,12 @@
import "./HTMLElement.prototype.prepend";
import { Deferred } from "evt/tools/Deferred";
export function appendHead(
export function headInsert(
params:
| {
type: "css";
href: string;
position: "append" | "prepend";
}
| {
type: "javascript";
@ -46,7 +48,23 @@ export function appendHead(
})(),
);
document.getElementsByTagName("head")[0].appendChild(htmlElement);
document.getElementsByTagName("head")[0][
(() => {
switch (params.type) {
case "javascript":
return "appendChild";
case "css":
return (() => {
switch (params.position) {
case "append":
return "appendChild";
case "prepend":
return "prepend";
}
})();
}
})()
](htmlElement);
return dLoaded.pr;
}