Skip to content

Commit 020d50b

Browse files
authored
Merge pull request #5 from marko-js/improve-safari-support
fix: fallback document impl in old safari
2 parents 2f9506e + 242470c commit 020d50b

File tree

3 files changed

+39
-3
lines changed

3 files changed

+39
-3
lines changed

README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,6 @@ An alternative API is also available to use in case legacy browsers not implemen
6767

6868
The following is a version of the previous example implemented using the alternative API.
6969

70-
7170
```js
7271
import writableDOM from "writable-dom";
7372

package-lock.json

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/index.ts

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,37 @@ type Writable = {
44
close(): Promise<void>;
55
};
66

7+
const createHTMLDocument = () => document.implementation.createHTMLDocument("");
8+
let createDocument = (
9+
target: ParentNode,
10+
nextSibling: ChildNode | null
11+
): Document => {
12+
const testDoc = createHTMLDocument();
13+
testDoc.write("<script>");
14+
/**
15+
* Safari and potentially other browsers strip script tags from detached documents.
16+
* If that's the case we'll fallback to an iframe implementation.
17+
*/
18+
createDocument = testDoc.scripts.length
19+
? createHTMLDocument
20+
: (target, nextSibling) => {
21+
const frame = document.createElement("iframe");
22+
frame.src = "";
23+
frame.style.display = "none";
24+
target.insertBefore(frame, nextSibling);
25+
const doc = frame.contentDocument!;
26+
const { close } = doc;
27+
doc.close = () => {
28+
target.removeChild(frame);
29+
close.call(doc);
30+
};
31+
32+
return doc;
33+
};
34+
35+
return createDocument(target, nextSibling);
36+
};
37+
738
export = function writableDOM(
839
this: unknown,
940
target: ParentNode,
@@ -13,12 +44,12 @@ export = function writableDOM(
1344
return new WritableStream(writableDOM(target, previousSibling));
1445
}
1546

16-
const doc = document.implementation.createHTMLDocument("");
47+
const nextSibling = previousSibling ? previousSibling.nextSibling : null;
48+
const doc = createDocument(target, nextSibling);
1749
doc.write("<!DOCTYPE html><body><template>");
1850
const root = (doc.body.firstChild as HTMLTemplateElement).content;
1951
const walker = doc.createTreeWalker(root);
2052
const targetNodes = new WeakMap<Node, Node>([[root, target]]);
21-
const nextSibling = previousSibling ? previousSibling.nextSibling : null;
2253
let pendingText: Text | null = null;
2354
let scanNode: Node | null = null;
2455
let resolve: void | (() => void);

0 commit comments

Comments
 (0)