Skip to content

Commit 6ec2398

Browse files
ledsunkateinoigakukun
authored andcommitted
Improve loading of Ruby scripts when using the src attribute
- Parallelization of downloads - Error response handling - URL encoding
1 parent 2846a54 commit 6ec2398

File tree

1 file changed

+29
-11
lines changed

1 file changed

+29
-11
lines changed

packages/npm-packages/ruby-wasm-wasi/src/browser.script.ts

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,35 @@ export const main = async (pkg: { name: string; version: string }) => {
1616
};
1717

1818
const runRubyScriptsInHtml = async (vm) => {
19-
const tags = document.getElementsByTagName("script");
20-
for (var i = 0, len = tags.length; i < len; i++) {
21-
const tag = tags[i];
22-
if (tag.type === "text/ruby") {
23-
if (tag.hasAttribute("src")) {
24-
const response = await fetch(tag.getAttribute("src"));
25-
const rubyScript = await response.text();
26-
vm.eval(rubyScript);
27-
} else if (tag.innerHTML) {
28-
vm.eval(tag.innerHTML);
29-
}
19+
const tags = document.querySelectorAll('script[type="text/ruby"]');
20+
21+
// Get Ruby scripts in parallel.
22+
const promisingRubyScripts = Array.from(tags).map((tag) =>
23+
loadScriptAsync(tag)
24+
);
25+
26+
// Run Ruby scripts sequentially.
27+
for await (const rubyScript of promisingRubyScripts) {
28+
if (rubyScript) {
29+
vm.eval(rubyScript);
30+
}
31+
}
32+
};
33+
34+
const loadScriptAsync = async (tag: Element): Promise<string> => {
35+
// Inline comments can be written with the src attribute of the script tag.
36+
// The presence of the src attribute is checked before the presence of the inline.
37+
// see: https://html.spec.whatwg.org/multipage/scripting.html#inline-documentation-for-external-scripts
38+
if (tag.hasAttribute("src")) {
39+
const url = encodeURI(tag.getAttribute("src"));
40+
const response = await fetch(url);
41+
42+
if (response.ok) {
43+
return await response.text();
3044
}
45+
46+
return Promise.resolve("");
3147
}
48+
49+
return Promise.resolve(tag.innerHTML);
3250
};

0 commit comments

Comments
 (0)