<link>
标签用于在 HTML 文档中引入外部资源,如 CSS 样式表。动态加载 CSS 样式表是指在页面加载后,通过 JavaScript 动态地插入 <link>
标签,从而加载并应用 CSS 样式。
<link>
标签<style>
标签中rel="preload"
预加载 CSS 文件<link>
标签function loadCSS(url) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
document.head.appendChild(link);
}
// 使用示例
loadCSS('https://example.com/styles.css');
<style>
标签中function loadCSS(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(xhr.responseText));
document.head.appendChild(style);
}
};
xhr.send();
}
// 使用示例
loadCSS('https://example.com/styles.css');
原因:
解决方法:
DOMContentLoaded
事件触发后再插入 <link>
标签。document.addEventListener('DOMContentLoaded', function() {
loadCSS('https://example.com/styles.css');
});
原因:
解决方法:
rel="preload"
预加载关键 CSS 文件。<link rel="preload" href="https://example.com/critical-styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
通过以上方法,你可以有效地动态加载 CSS 样式表,并解决常见的加载和应用问题。
领取专属 10元无门槛券
手把手带您无忧上云