mirror of
https://github.com/django-components/django-components.git
synced 2025-09-26 15:39:08 +00:00
fix: Fix broken JS execution order (#821)
* fix: fix broken js exec order * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * refactor: remove stale comment --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
parent
e88e3af27f
commit
be27c1c94d
15 changed files with 833 additions and 379 deletions
|
@ -6,6 +6,7 @@ import sys
|
|||
from abc import ABC, abstractmethod
|
||||
from functools import lru_cache
|
||||
from hashlib import md5
|
||||
from textwrap import dedent
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Callable,
|
||||
|
@ -492,16 +493,25 @@ def _process_dep_declarations(content: bytes, type: RenderType) -> Tuple[bytes,
|
|||
loaded_css_urls = sorted(
|
||||
[
|
||||
*loaded_component_css_urls,
|
||||
# NOTE: Unlike JS, the initial CSS is loaded outside of the dependency
|
||||
# manager, and only marked as loaded, to avoid a flash of unstyled content.
|
||||
*to_load_css_urls,
|
||||
# NOTE: When rendering a document, the initial CSS is inserted directly into the HTML
|
||||
# to avoid a flash of unstyled content. In the dependency manager, we only mark those
|
||||
# scripts as loaded.
|
||||
*(to_load_css_urls if type == "document" else []),
|
||||
]
|
||||
)
|
||||
loaded_js_urls = sorted(
|
||||
[
|
||||
*loaded_component_js_urls,
|
||||
# NOTE: When rendering a document, the initial JS is inserted directly into the HTML
|
||||
# so the scripts are executed at proper order. In the dependency manager, we only mark those
|
||||
# scripts as loaded.
|
||||
*(to_load_js_urls if type == "document" else []),
|
||||
]
|
||||
)
|
||||
loaded_js_urls = sorted(loaded_component_js_urls)
|
||||
|
||||
exec_script = _gen_exec_script(
|
||||
to_load_js_tags=to_load_js_tags,
|
||||
to_load_css_tags=to_load_css_tags,
|
||||
to_load_js_tags=to_load_js_tags if type == "fragment" else [],
|
||||
to_load_css_tags=to_load_css_tags if type == "fragment" else [],
|
||||
loaded_js_urls=loaded_js_urls,
|
||||
loaded_css_urls=loaded_css_urls,
|
||||
)
|
||||
|
@ -511,24 +521,37 @@ def _process_dep_declarations(content: bytes, type: RenderType) -> Tuple[bytes,
|
|||
js=[static("django_components/django_components.min.js")],
|
||||
).render_js()
|
||||
|
||||
final_script_tags = b"".join(
|
||||
final_script_tags = "".join(
|
||||
[
|
||||
*[tag.encode("utf-8") for tag in core_script_tags],
|
||||
*[tag.encode("utf-8") for tag in inlined_component_js_tags],
|
||||
exec_script.encode("utf-8"),
|
||||
# JS by us
|
||||
*[tag for tag in core_script_tags],
|
||||
# Make calls to the JS dependency manager
|
||||
# Loads JS from `Media.js` and `Component.js` if fragment
|
||||
exec_script,
|
||||
# JS from `Media.js`
|
||||
# NOTE: When rendering a document, the initial JS is inserted directly into the HTML
|
||||
# so the scripts are executed at proper order. In the dependency manager, we only mark those
|
||||
# scripts as loaded.
|
||||
*(to_load_js_tags if type == "document" else []),
|
||||
# JS from `Component.js` (if not fragment)
|
||||
*[tag for tag in inlined_component_js_tags],
|
||||
]
|
||||
)
|
||||
|
||||
final_css_tags = b"".join(
|
||||
final_css_tags = "".join(
|
||||
[
|
||||
*[tag.encode("utf-8") for tag in inlined_component_css_tags],
|
||||
# NOTE: Unlike JS, the initial CSS is loaded outside of the dependency
|
||||
# manager, and only marked as loaded, to avoid a flash of unstyled content.
|
||||
*[tag.encode("utf-8") for tag in to_load_css_tags],
|
||||
# CSS by us
|
||||
# <NONE>
|
||||
# CSS from `Component.css` (if not fragment)
|
||||
*[tag for tag in inlined_component_css_tags],
|
||||
# CSS from `Media.css` (plus from `Component.css` if fragment)
|
||||
# NOTE: Similarly to JS, the initial CSS is loaded outside of the dependency
|
||||
# manager, and only marked as loaded, to avoid a flash of unstyled content.
|
||||
*[tag for tag in to_load_css_tags],
|
||||
]
|
||||
)
|
||||
|
||||
return content, final_script_tags, final_css_tags
|
||||
return (content, final_script_tags.encode("utf-8"), final_css_tags.encode("utf-8"))
|
||||
|
||||
|
||||
def _is_nonempty_str(txt: Optional[str]) -> bool:
|
||||
|
@ -551,8 +574,9 @@ def _postprocess_media_tags(
|
|||
|
||||
if not _is_nonempty_str(maybe_url):
|
||||
raise RuntimeError(
|
||||
f"One of entries for `Component.Media.{script_type}` media is missing "
|
||||
f"value for attribute '{attr}'. Got:\n{tag}"
|
||||
f"One of entries for `Component.Media.{script_type}` media is missing a "
|
||||
f"value for attribute '{attr}'. If there is content inlined inside the `<{node.tag}>` tags, "
|
||||
f"you must move the content to a `.{script_type}` file and reference it via '{attr}'.\nGot:\n{tag}"
|
||||
)
|
||||
|
||||
url = cast(str, maybe_url)
|
||||
|
@ -595,21 +619,21 @@ def _prepare_tags_and_urls(
|
|||
if type == "document":
|
||||
# NOTE: Skip fetching of inlined JS/CSS if it's not defined or empty for given component
|
||||
if _is_nonempty_str(comp_cls.js):
|
||||
inlined_js_tags.append(_get_script("js", comp_cls, type="tag"))
|
||||
loaded_js_urls.append(_get_script("js", comp_cls, type="url"))
|
||||
inlined_js_tags.append(_get_script_tag("js", comp_cls))
|
||||
loaded_js_urls.append(get_script_url("js", comp_cls))
|
||||
|
||||
if _is_nonempty_str(comp_cls.css):
|
||||
inlined_css_tags.append(_get_script("css", comp_cls, type="tag"))
|
||||
loaded_css_urls.append(_get_script("css", comp_cls, type="url"))
|
||||
inlined_css_tags.append(_get_script_tag("css", comp_cls))
|
||||
loaded_css_urls.append(get_script_url("css", comp_cls))
|
||||
|
||||
# When NOT a document (AKA is a fragment), then scripts are NOT inserted into
|
||||
# the HTML, and instead we fetch and load them all via our JS dependency manager.
|
||||
else:
|
||||
if _is_nonempty_str(comp_cls.js):
|
||||
to_load_js_urls.append(_get_script("js", comp_cls, type="url"))
|
||||
to_load_js_urls.append(get_script_url("js", comp_cls))
|
||||
|
||||
if _is_nonempty_str(comp_cls.css):
|
||||
loaded_css_urls.append(_get_script("css", comp_cls, type="url"))
|
||||
loaded_css_urls.append(get_script_url("css", comp_cls))
|
||||
|
||||
return (
|
||||
to_load_js_urls,
|
||||
|
@ -621,32 +645,45 @@ def _prepare_tags_and_urls(
|
|||
)
|
||||
|
||||
|
||||
def _get_script(
|
||||
def get_script_content(
|
||||
script_type: ScriptType,
|
||||
comp_cls: Type["Component"],
|
||||
type: Literal["url", "tag"],
|
||||
) -> Union[str, SafeString]:
|
||||
) -> SafeString:
|
||||
comp_cls_hash = _hash_comp_cls(comp_cls)
|
||||
cache_key = _gen_cache_key(comp_cls_hash, script_type)
|
||||
script = comp_media_cache.get(cache_key)
|
||||
|
||||
return script
|
||||
|
||||
|
||||
def _get_script_tag(
|
||||
script_type: ScriptType,
|
||||
comp_cls: Type["Component"],
|
||||
) -> SafeString:
|
||||
script = get_script_content(script_type, comp_cls)
|
||||
|
||||
if script_type == "js":
|
||||
return f"<script>{_escape_js(script)}</script>"
|
||||
|
||||
elif script_type == "css":
|
||||
return f"<style>{script}</style>"
|
||||
|
||||
return script
|
||||
|
||||
|
||||
def get_script_url(
|
||||
script_type: ScriptType,
|
||||
comp_cls: Type["Component"],
|
||||
) -> str:
|
||||
comp_cls_hash = _hash_comp_cls(comp_cls)
|
||||
|
||||
if type == "url":
|
||||
# NOTE: To make sure that Media object won't modify the URLs, we need to
|
||||
# resolve the full path (`/abc/def/etc`), not just the file name.
|
||||
script = reverse(
|
||||
CACHE_ENDPOINT_NAME,
|
||||
kwargs={
|
||||
"comp_cls_hash": comp_cls_hash,
|
||||
"script_type": script_type,
|
||||
},
|
||||
)
|
||||
else:
|
||||
cache_key = _gen_cache_key(comp_cls_hash, script_type)
|
||||
script = comp_media_cache.get(cache_key)
|
||||
|
||||
if script_type == "js":
|
||||
script = mark_safe(f"<script>{_escape_js(script)}</script>")
|
||||
elif script_type == "css":
|
||||
script = mark_safe(f"<style>{script}</style>")
|
||||
return script
|
||||
return reverse(
|
||||
CACHE_ENDPOINT_NAME,
|
||||
kwargs={
|
||||
"comp_cls_hash": comp_cls_hash,
|
||||
"script_type": script_type,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _gen_exec_script(
|
||||
|
@ -658,9 +695,9 @@ def _gen_exec_script(
|
|||
# Generate JS expression like so:
|
||||
# ```js
|
||||
# Promise.all([
|
||||
# Components.manager.loadScript("js", '<script src="/abc/def1">...</script>'),
|
||||
# Components.manager.loadScript("js", '<script src="/abc/def2">...</script>'),
|
||||
# Components.manager.loadScript("css", '<link href="/abc/def3">'),
|
||||
# Components.manager.loadJs('<script src="/abc/def1">...</script>'),
|
||||
# Components.manager.loadJs('<script src="/abc/def2">...</script>'),
|
||||
# Components.manager.loadCss('<link href="/abc/def3">'),
|
||||
# ]);
|
||||
# ```
|
||||
#
|
||||
|
@ -672,13 +709,9 @@ def _gen_exec_script(
|
|||
# Components.manager.markScriptLoaded("js", "/abc/def3.js"),
|
||||
# ```
|
||||
#
|
||||
# NOTE: It would be better to pass only the URL itself for `loadScript`, instead of a whole tag.
|
||||
# But because we allow users to specify the Media class, and thus users can
|
||||
# configure how the `<link>` or `<script>` tags are rendered, we need pass the whole tag.
|
||||
#
|
||||
# NOTE 2: We must NOT await for the Promises, otherwise we create a deadlock
|
||||
# where the script loaded with `loadScript` (loadee) is inserted AFTER the script with `loadScript` (loader).
|
||||
# But the loader will NOT finish, because it's waiting for loadee, which cannot start before loader ends.
|
||||
# NOTE: It would be better to pass only the URL itself for `loadJs/loadCss`, instead of a whole tag.
|
||||
# But because we allow users to specify the Media class, and thus users can
|
||||
# configure how the `<link>` or `<script>` tags are rendered, we need pass the whole tag.
|
||||
escaped_to_load_js_tags = [_escape_js(tag, eval=False) for tag in to_load_js_tags]
|
||||
escaped_to_load_css_tags = [_escape_js(tag, eval=False) for tag in to_load_css_tags]
|
||||
|
||||
|
@ -686,25 +719,23 @@ def _gen_exec_script(
|
|||
def js_arr(lst: List) -> str:
|
||||
return "[" + ", ".join(lst) + "]"
|
||||
|
||||
exec_script: types.js = f"""(() => {{
|
||||
const loadedJsScripts = {json.dumps(loaded_js_urls)};
|
||||
const loadedCssScripts = {json.dumps(loaded_css_urls)};
|
||||
const toLoadJsScripts = {js_arr(escaped_to_load_js_tags)};
|
||||
const toLoadCssScripts = {js_arr(escaped_to_load_css_tags)};
|
||||
|
||||
loadedJsScripts.forEach((s) => Components.manager.markScriptLoaded("js", s));
|
||||
loadedCssScripts.forEach((s) => Components.manager.markScriptLoaded("css", s));
|
||||
|
||||
Promise.all(
|
||||
toLoadJsScripts.map((s) => Components.manager.loadScript("js", s))
|
||||
).catch(console.error);
|
||||
Promise.all(
|
||||
toLoadCssScripts.map((s) => Components.manager.loadScript("css", s))
|
||||
).catch(console.error);
|
||||
}})();
|
||||
# NOTE: Wrap the body in self-executing function to avoid polluting the global scope.
|
||||
exec_script: types.js = f"""
|
||||
(() => {{
|
||||
Components.manager._loadComponentScripts({{
|
||||
loadedCssUrls: {json.dumps(loaded_css_urls)},
|
||||
loadedJsUrls: {json.dumps(loaded_js_urls)},
|
||||
toLoadCssTags: {js_arr(escaped_to_load_css_tags)},
|
||||
toLoadJsTags: {js_arr(escaped_to_load_js_tags)},
|
||||
}});
|
||||
document.currentScript.remove();
|
||||
}})();
|
||||
"""
|
||||
|
||||
exec_script = f"<script>{_escape_js(exec_script)}</script>"
|
||||
# NOTE: The exec script MUST be executed SYNC, so we MUST NOT put `type="module"`,
|
||||
# `async`, nor `defer` on it.
|
||||
# See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#notes
|
||||
exec_script = f"<script>{_escape_js(dedent(exec_script))}</script>"
|
||||
return exec_script
|
||||
|
||||
|
||||
|
|
|
@ -1 +1 @@
|
|||
(()=>{var y=Array.isArray,p=t=>typeof t=="function",M=t=>t!==null&&typeof t=="object",h=t=>(M(t)||p(t))&&p(t.then)&&p(t.catch);function S(t,a){try{return a?t.apply(null,a):t()}catch(r){f(r)}}function m(t,a){if(p(t)){let r=S(t,a);return r&&h(r)&&r.catch(i=>{f(i)}),[r]}if(y(t)){let r=[];for(let i=0;i<t.length;i++)r.push(m(t[i],a));return r}else console.warn(`[Components] Invalid value type passed to callWithAsyncErrorHandling(): ${typeof t}`)}function f(t){console.error(t)}var u=()=>{let t=new Set,a=new Set,r={},i={},C=e=>{let n=new DOMParser().parseFromString(e,"text/html").querySelector("script");if(!n)throw Error("[Components] Failed to extract <script> tag. Make sure that the string contains <script><\/script> and is a valid HTML");return n},x=e=>{let n=new DOMParser().parseFromString(e,"text/html").querySelector("link");if(!n)throw Error("[Components] Failed to extract <link> tag. Make sure that the string contains <link></link> and is a valid HTML");return n},g=e=>{let n=document.createElement(e.tagName);for(let o of e.attributes)n.setAttributeNode(o.cloneNode());return n};return{callComponent:(e,n,o)=>{let s=r[e];if(!s)throw Error(`[Components] '${e}': No component registered for that name`);let c=Array.from(document.querySelectorAll(`[data-comp-id-${n}]`));if(!c.length)throw Error(`[Components] '${e}': No elements with component ID '${n}' found`);let l=`${e}:${o}`,d=i[l];if(!d)throw Error(`[Components] '${e}': Cannot find input for hash '${o}'`);let T=d(),E={name:e,id:n,els:c},[F]=m(s,[T,E]);return F},registerComponent:(e,n)=>{r[e]=n},registerComponentData:(e,n,o)=>{let s=`${e}:${n}`;i[s]=o},loadScript:(e,n)=>{if(e==="js"){let o=C(n),s=o.getAttribute("src");if(!s||t.has(s))return;t.add(s);let c=g(o);return new Promise((l,d)=>{c.onload=()=>{l()},globalThis.document.body.append(c)})}else if(e==="css"){let o=x(n),s=o.getAttribute("href");if(!s||a.has(s))return;let c=g(o);return globalThis.document.head.append(c),a.add(s),Promise.resolve()}else throw Error(`[Components] loadScript received invalid script type '${e}'. Must be one of 'js', 'css'`)},markScriptLoaded:(e,n)=>{if(e==="js")t.add(n);else if(e==="css")a.add(n);else throw Error(`[Components] markScriptLoaded received invalid script type '${e}'. Must be one of 'js', 'css'`)}}};var w={manager:u(),createComponentsManager:u,unescapeJs:r=>new DOMParser().parseFromString(r,"text/html").documentElement.textContent};globalThis.Components=w;})();
|
||||
(()=>{var x=Array.isArray,l=n=>typeof n=="function",w=n=>n!==null&&typeof n=="object",E=n=>(w(n)||l(n))&&l(n.then)&&l(n.catch);function j(n,a){try{return a?n.apply(null,a):n()}catch(r){S(r)}}function g(n,a){if(l(n)){let r=j(n,a);return r&&E(r)&&r.catch(i=>{S(i)}),[r]}if(x(n)){let r=[];for(let i=0;i<n.length;i++)r.push(g(n[i],a));return r}else console.warn(`[Components] Invalid value type passed to callWithAsyncErrorHandling(): ${typeof n}`)}function S(n){console.error(n)}var u=()=>{let n=new Set,a=new Set,r={},i={},b=t=>{let e=new DOMParser().parseFromString(t,"text/html").querySelector("script");if(!e)throw Error("[Components] Failed to extract <script> tag. Make sure that the string contains <script><\/script> and is a valid HTML");return e},M=t=>{let e=new DOMParser().parseFromString(t,"text/html").querySelector("link");if(!e)throw Error("[Components] Failed to extract <link> tag. Make sure that the string contains <link></link> and is a valid HTML");return e},y=t=>{let e=document.createElement(t.tagName);e.innerHTML=t.innerHTML;for(let o of t.attributes)e.setAttributeNode(o.cloneNode());return e},h=t=>{let e=b(t),o=e.getAttribute("src");if(!o||T("js",o))return;c("js",o);let s=y(e),p=e.getAttribute("async")!=null||e.getAttribute("defer")!=null||e.getAttribute("type")==="module";s.async=p;let m=new Promise((d,f)=>{s.onload=()=>{d()},globalThis.document.body.append(s)});return{el:s,promise:m}},C=t=>{let e=M(t),o=e.getAttribute("href");if(!o||T("css",o))return;let s=y(e);return globalThis.document.head.append(s),c("css",o),{el:s,promise:Promise.resolve()}},c=(t,e)=>{if(t!=="js"&&t!=="css")throw Error(`[Components] markScriptLoaded received invalid script type '${t}'. Must be one of 'js', 'css'`);(t==="js"?n:a).add(e)},T=(t,e)=>{if(t!=="js"&&t!=="css")throw Error(`[Components] isScriptLoaded received invalid script type '${t}'. Must be one of 'js', 'css'`);return(t==="js"?n:a).has(e)};return{callComponent:(t,e,o)=>{let s=r[t];if(!s)throw Error(`[Components] '${t}': No component registered for that name`);let p=Array.from(document.querySelectorAll(`[data-comp-id-${e}]`));if(!p.length)throw Error(`[Components] '${t}': No elements with component ID '${e}' found`);let m=`${t}:${o}`,d=i[m];if(!d)throw Error(`[Components] '${t}': Cannot find input for hash '${o}'`);let f=d(),F={name:t,id:e,els:p},[L]=g(s,[f,F]);return L},registerComponent:(t,e)=>{r[t]=e},registerComponentData:(t,e,o)=>{let s=`${t}:${e}`;i[s]=o},loadJs:h,loadCss:C,markScriptLoaded:c,_loadComponentScripts:async t=>{t.loadedCssUrls.forEach(o=>c("css",o)),t.loadedJsUrls.forEach(o=>c("js",o)),Promise.all(t.toLoadCssTags.map(o=>C(o))).catch(console.error);let e=Promise.all(t.toLoadJsTags.map(o=>h(o))).catch(console.error)}}};var k={manager:u(),createComponentsManager:u,unescapeJs:r=>new DOMParser().parseFromString(r,"text/html").documentElement.textContent};globalThis.Components=k;})();
|
||||
|
|
|
@ -32,10 +32,10 @@ Components.callComponent(
|
|||
);
|
||||
|
||||
// Load JS or CSS script if not laoded already
|
||||
Components.loadScript("js", '<script src="/abc/def">');
|
||||
Components.loadJs('<script src="/abc/def">');
|
||||
|
||||
// Or mark one as already-loaded, so it is ignored when
|
||||
// we call `loadScript`
|
||||
// we call `loadJs`
|
||||
Components.markScriptLoaded("js", '/abc/def');
|
||||
```
|
||||
|
||||
|
|
|
@ -43,7 +43,11 @@ export type ScriptType = 'js' | 'css';
|
|||
* ```
|
||||
*
|
||||
* ```js
|
||||
* Components.loadScript("js", '<script src="/abc/def"></script>');
|
||||
* Components.loadJs('<script src="/abc/def"></script>');
|
||||
* ```
|
||||
*
|
||||
* ```js
|
||||
* Components.loadCss('<link href="/abc/def" />');
|
||||
* ```
|
||||
*
|
||||
* ```js
|
||||
|
@ -84,68 +88,104 @@ export const createComponentsManager = () => {
|
|||
// one to the other.
|
||||
// Might be related to https://security.stackexchange.com/a/240362/302733
|
||||
// See https://stackoverflow.com/questions/13121948
|
||||
const cloneNode = (srcNode: HTMLElement) => {
|
||||
const targetNode = document.createElement(srcNode.tagName);
|
||||
const cloneNode = <T extends HTMLElement>(srcNode: T): T => {
|
||||
const targetNode = document.createElement(srcNode.tagName) as T;
|
||||
targetNode.innerHTML = srcNode.innerHTML;
|
||||
for (const attr of srcNode.attributes) {
|
||||
targetNode.setAttributeNode(attr.cloneNode() as Attr);
|
||||
}
|
||||
return targetNode;
|
||||
};
|
||||
|
||||
const loadScript = (type: ScriptType, tag: string) => {
|
||||
if (type === 'js') {
|
||||
const srcScriptNode = parseScriptTag(tag);
|
||||
const loadJs = (tag: string) => {
|
||||
const srcScriptNode = parseScriptTag(tag);
|
||||
|
||||
// Use `.getAttribute()` instead of `.src` so we get the value as is,
|
||||
// without the host name prepended if URL is just a path.
|
||||
const src = srcScriptNode.getAttribute('src');
|
||||
if (!src || loadedJs.has(src)) return;
|
||||
// Use `.getAttribute()` instead of `.src` so we get the value as is,
|
||||
// without the host name prepended if URL is just a path.
|
||||
const src = srcScriptNode.getAttribute('src');
|
||||
if (!src || isScriptLoaded('js', src)) return;
|
||||
|
||||
loadedJs.add(src);
|
||||
markScriptLoaded('js', src);
|
||||
|
||||
const targetScriptNode = cloneNode(srcScriptNode);
|
||||
const targetScriptNode = cloneNode(srcScriptNode);
|
||||
|
||||
// In case of JS scripts, we return a Promise that resolves when the script is loaded
|
||||
// See https://stackoverflow.com/a/57267538/9788634
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
targetScriptNode.onload = () => {
|
||||
resolve();
|
||||
};
|
||||
const isAsync = (
|
||||
// NOTE: `async` and `defer` are boolean attributes, so their value can be
|
||||
// an empty string, hence the `!= null` check.
|
||||
// Read more on https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
|
||||
srcScriptNode.getAttribute('async') != null
|
||||
|| srcScriptNode.getAttribute('defer') != null
|
||||
|| srcScriptNode.getAttribute('type') === 'module'
|
||||
);
|
||||
|
||||
// Insert the script at the end of <body> to follow convention
|
||||
globalThis.document.body.append(targetScriptNode);
|
||||
});
|
||||
} else if (type === 'css') {
|
||||
const linkNode = parseLinkTag(tag);
|
||||
// NOTE: Use `.getAttribute()` instead of `.href` so we get the value as is,
|
||||
// without the host name prepended if URL is just a path.
|
||||
const href = linkNode.getAttribute('href');
|
||||
if (!href || loadedCss.has(href)) return;
|
||||
// Setting this to `false` ensures that the loading and execution of the script is "blocking",
|
||||
// meaning that the next script in line will wait until this one is done.
|
||||
// See https://stackoverflow.com/a/21550322/9788634
|
||||
targetScriptNode.async = isAsync;
|
||||
|
||||
// Insert at the end of <head> to follow convention
|
||||
const targetLinkNode = cloneNode(linkNode);
|
||||
globalThis.document.head.append(targetLinkNode);
|
||||
loadedCss.add(href);
|
||||
// In case of JS scripts, we return a Promise that resolves when the script is loaded
|
||||
// See https://stackoverflow.com/a/57267538/9788634
|
||||
const promise = new Promise<void>((resolve, reject) => {
|
||||
targetScriptNode.onload = () => {
|
||||
resolve();
|
||||
};
|
||||
|
||||
// For CSS, we return a dummy Promise, since we don't need to wait for anything
|
||||
return Promise.resolve();
|
||||
} else {
|
||||
throw Error(
|
||||
`[Components] loadScript received invalid script type '${type}'. Must be one of 'js', 'css'`
|
||||
);
|
||||
}
|
||||
// Insert at the end of `<body>` to follow convention
|
||||
//
|
||||
// NOTE: Because we are inserting the script into the DOM from within JS,
|
||||
// the order of execution of the inserted scripts behaves a bit different:
|
||||
// - The `<script>` that were originally in the HTML file will run in the order they appear in the file.
|
||||
// And they will run BEFORE the dynamically inserted scripts.
|
||||
// - The order of execution of the dynamically inserted scripts depends on the order of INSERTION,
|
||||
// and NOT on WHERE we insert the script in the DOM.
|
||||
globalThis.document.body.append(targetScriptNode);
|
||||
});
|
||||
|
||||
return {
|
||||
el: targetScriptNode,
|
||||
promise,
|
||||
};
|
||||
};
|
||||
|
||||
const markScriptLoaded = (type: ScriptType, url: string) => {
|
||||
if (type === 'js') {
|
||||
loadedJs.add(url);
|
||||
} else if (type === 'css') {
|
||||
loadedCss.add(url);
|
||||
} else {
|
||||
const loadCss = (tag: string) => {
|
||||
const linkNode = parseLinkTag(tag);
|
||||
// NOTE: Use `.getAttribute()` instead of `.href` so we get the value as is,
|
||||
// without the host name prepended if URL is just a path.
|
||||
const href = linkNode.getAttribute('href');
|
||||
if (!href || isScriptLoaded('css', href)) return;
|
||||
|
||||
// Insert at the end of <head> to follow convention
|
||||
const targetLinkNode = cloneNode(linkNode);
|
||||
globalThis.document.head.append(targetLinkNode);
|
||||
markScriptLoaded('css', href);
|
||||
|
||||
// For CSS, we return a dummy Promise, since we don't need to wait for anything
|
||||
return {
|
||||
el: targetLinkNode,
|
||||
promise: Promise.resolve(),
|
||||
};
|
||||
};
|
||||
|
||||
const markScriptLoaded = (type: ScriptType, url: string): void => {
|
||||
if (type !== 'js' && type !== 'css') {
|
||||
throw Error(
|
||||
`[Components] markScriptLoaded received invalid script type '${type}'. Must be one of 'js', 'css'`
|
||||
);
|
||||
}
|
||||
|
||||
const urlsSet = type === 'js' ? loadedJs : loadedCss;
|
||||
urlsSet.add(url);
|
||||
};
|
||||
|
||||
const isScriptLoaded = (type: ScriptType, url: string): boolean => {
|
||||
if (type !== 'js' && type !== 'css') {
|
||||
throw Error(
|
||||
`[Components] isScriptLoaded received invalid script type '${type}'. Must be one of 'js', 'css'`
|
||||
);
|
||||
}
|
||||
|
||||
const urlsSet = type === 'js' ? loadedJs : loadedCss;
|
||||
return urlsSet.has(url);
|
||||
};
|
||||
|
||||
const registerComponent = (name: string, compFn: ComponentFn) => {
|
||||
|
@ -186,11 +226,38 @@ export const createComponentsManager = () => {
|
|||
return result;
|
||||
};
|
||||
|
||||
/** Internal API - We call this when we want to load / register all JS & CSS files rendered by component(s) */
|
||||
const _loadComponentScripts = async (inputs: {
|
||||
loadedCssUrls: string[];
|
||||
loadedJsUrls: string[];
|
||||
toLoadCssTags: string[];
|
||||
toLoadJsTags: string[];
|
||||
}) => {
|
||||
// Mark as loaded the CSS that WAS inlined into the HTML.
|
||||
inputs.loadedCssUrls.forEach((s) => markScriptLoaded("css", s));
|
||||
inputs.loadedJsUrls.forEach((s) => markScriptLoaded("js", s));
|
||||
|
||||
// Load CSS that was not inlined into the HTML
|
||||
// NOTE: We don't need to wait for CSS to load
|
||||
Promise
|
||||
.all(inputs.toLoadCssTags.map((s) => loadCss(s)))
|
||||
.catch(console.error);
|
||||
|
||||
// Load JS that was not inlined into the HTML
|
||||
const jsScriptsPromise = Promise
|
||||
// NOTE: Interestingly enough, when we insert scripts into the DOM programmatically,
|
||||
// the order of execution is the same as the order of insertion.
|
||||
.all(inputs.toLoadJsTags.map((s) => loadJs(s)))
|
||||
.catch(console.error);
|
||||
};
|
||||
|
||||
return {
|
||||
callComponent,
|
||||
registerComponent,
|
||||
registerComponentData,
|
||||
loadScript,
|
||||
loadJs,
|
||||
loadCss,
|
||||
markScriptLoaded,
|
||||
_loadComponentScripts,
|
||||
};
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue