Skip to content

Commit 665f9be

Browse files
committed
✨ Install Socket.IO from CDN
1 parent 7e4bff6 commit 665f9be

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

socket.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/// <reference no-default-lib="true" />
2+
/// <reference lib="esnext" />
3+
/// <reference lib="dom" />
4+
import type {
5+
Manager,
6+
ManagerOptions,
7+
Socket,
8+
SocketOptions,
9+
} from "https://cdn.esm.sh/v54/socket.io-client@4.2.0/build/index.d.ts";
10+
export type { Manager, ManagerOptions, Socket, SocketOptions };
11+
12+
declare function io(
13+
uri: string,
14+
opts?: Partial<ManagerOptions & SocketOptions>,
15+
): Socket;
16+
const version = "4.2.0";
17+
18+
export async function socketIO() {
19+
const io = await importSocketIO();
20+
return io("https://scrapbox.io", {
21+
reconnectionDelay: 5000,
22+
transports: ["websocket"],
23+
});
24+
}
25+
26+
function importSocketIO(): Promise<typeof io> {
27+
const url =
28+
`https://cdnjs.cloudflare.com/ajax/libs/socket.io/${version}/socket.io.min.js`;
29+
if (document.querySelector(`script[src="${url}"]`)) {
30+
return Promise.resolve(io);
31+
}
32+
33+
const script = document.createElement("script");
34+
script.src = url;
35+
return new Promise((resolve, reject) => {
36+
script.onload = () => resolve(io);
37+
script.onerror = (e) => reject(e);
38+
document.head.append(script);
39+
});
40+
}

0 commit comments

Comments
 (0)