如何用原生JavaScript在Spotfire中实现CSS按需加载(替代jQuery)
原生JavaScript实现CSS按需加载(替代Spotfire中的jQuery方案)
你可以用以下原生JavaScript代码实现和原jQuery逻辑完全一致的功能——仅当DOM中不存在指定CSS文件的链接时才加载它:
const cssUrl = "https://localhost/css/style.css"; // 检查是否已存在该CSS链接 const existingLink = document.querySelector(`link[href="${cssUrl}"]`); if (!existingLink) { // 创建link元素并设置属性 const link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = cssUrl; // 将元素添加到head标签 document.head.appendChild(link); }
代码说明
- 用
document.querySelector()替代jQuery的选择器语法,精准查询是否存在对应href的<link>标签 - 当查询结果为
null(即无匹配标签)时,通过document.createElement()创建新的link元素 - 手动设置
rel、type、href属性,对应原jQuery代码中创建元素时的配置项 - 调用
document.head.appendChild()将新元素插入到head中,替代jQuery的appendTo("head")方法
内容的提问来源于stack exchange,提问作者Marcio Lino
相关产品推荐
相关产品推荐

