Skip to content

Commit 7f0e339

Browse files
authored
Merge pull request #243 from tuespetre/link-attributes
Fix #242: keep id,media,title attributes on replaced link elements
2 parents 3ca0e2c + c167df4 commit 7f0e339

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/transform.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,16 @@ export async function transformCSS(
1212
if (el.tagName.toLowerCase() === 'style') {
1313
// Handle inline stylesheets
1414
el.innerHTML = css;
15-
} else if (el.tagName.toLowerCase() === 'link') {
15+
} else if (el instanceof HTMLLinkElement) {
1616
// Create new link
1717
const blob = new Blob([css], { type: 'text/css' });
1818
const url = URL.createObjectURL(blob);
1919
const link = document.createElement('link');
2020
link.rel = 'stylesheet';
2121
link.href = url;
22+
link.id = el.id;
23+
link.media = el.media;
24+
link.title = el.title;
2225
const promise = new Promise((res) => {
2326
link.onload = res;
2427
});

tests/unit/transform.test.ts

+18
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,22 @@ describe('transformCSS', () => {
4949
expect(div.hasAttribute('data-has-inline-styles')).toBeFalsy();
5050
expect(div2.hasAttribute('data-has-inline-styles')).toBeFalsy();
5151
});
52+
53+
it('preserves id, media, and title attributes when replacing link elements', async () => {
54+
document.head.innerHTML = `
55+
<link id="the-link" media="screen" title="stylish" rel="stylesheet" href="/sample.css"/>
56+
`;
57+
let link = document.querySelector('link') as HTMLLinkElement;
58+
const styleData = [{ el: link, css: 'html { margin: 0; }', changed: true }];
59+
const inlineStyles = new Map();
60+
const promise = transformCSS(styleData, inlineStyles, true);
61+
link = document.querySelector('link') as HTMLLinkElement;
62+
link.dispatchEvent(new Event('load'));
63+
await promise;
64+
65+
expect(link.href).toContain('/updated.css');
66+
expect(link.id).toBe('the-link');
67+
expect(link.media).toBe('screen');
68+
expect(link.title).toBe('stylish');
69+
});
5270
});

0 commit comments

Comments
 (0)