Skip to content

Commit 09680f6

Browse files
committed
feat: Not return undefined from importSocketIO()
1 parent a544619 commit 09680f6

File tree

1 file changed

+27
-15
lines changed

1 file changed

+27
-15
lines changed

socket.ts

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,22 @@ import type {
99
} from "./types/socketIO/index.ts";
1010
export type { Manager, ManagerOptions, Socket, SocketOptions };
1111

12+
type IO = (
13+
uri: string,
14+
opts?: Partial<ManagerOptions & SocketOptions>,
15+
) => Socket;
16+
1217
declare global {
1318
interface Window {
14-
io(
15-
uri: string,
16-
opts?: Partial<ManagerOptions & SocketOptions>,
17-
): Socket;
19+
io?: IO;
1820
}
1921
}
2022
const version = "4.2.0";
23+
const url =
24+
`https://cdnjs.cloudflare.com/ajax/libs/socket.io/${version}/socket.io.min.js`;
25+
let error: string | Event | undefined;
2126

22-
export async function socketIO() {
27+
export async function socketIO(): Promise<Socket> {
2328
const io = await importSocketIO();
2429
const socket = io("https://scrapbox.io", {
2530
reconnectionDelay: 5000,
@@ -37,18 +42,25 @@ export async function socketIO() {
3742
return socket;
3843
}
3944

40-
function importSocketIO(): Promise<Window["io"]> {
41-
const url =
42-
`https://cdnjs.cloudflare.com/ajax/libs/socket.io/${version}/socket.io.min.js`;
43-
if (document.querySelector(`script[src="${url}"]`)) {
44-
return Promise.resolve(window.io);
45+
async function importSocketIO(): Promise<IO> {
46+
if (!document.querySelector(`script[src="${url}"]`)) {
47+
const script = document.createElement("script");
48+
script.src = url;
49+
await new Promise<void>((resolve, reject) => {
50+
script.onload = () => resolve();
51+
script.onerror = (e) => {
52+
error = e;
53+
reject(e);
54+
};
55+
document.head.append(script);
56+
});
4557
}
4658

47-
const script = document.createElement("script");
48-
script.src = url;
4959
return new Promise((resolve, reject) => {
50-
script.onload = () => resolve(window.io);
51-
script.onerror = (e) => reject(e);
52-
document.head.append(script);
60+
const id = setInterval(() => {
61+
if (!window.io) return;
62+
clearInterval(id);
63+
resolve(window.io);
64+
}, 500);
5365
});
5466
}

0 commit comments

Comments
 (0)