Skip to content

Commit feb6675

Browse files
committed
Fix #242: keep id,media,title attributes on replaced link elements
1 parent f1d3bcc commit feb6675

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-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

+20
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,24 @@ 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 = [
59+
{ el: link, css: 'html { margin: 0; }', changed: true },
60+
];
61+
const inlineStyles = new Map();
62+
const promise = transformCSS(styleData, inlineStyles, true);
63+
link = document.querySelector('link') as HTMLLinkElement;
64+
link.dispatchEvent(new Event('load'));
65+
await promise;
66+
67+
expect(link.href).toContain('/updated.css');
68+
expect(link.id).toBe('the-link');
69+
expect(link.media).toBe('screen');
70+
expect(link.title).toBe('stylish');
71+
});
5272
});

0 commit comments

Comments
 (0)