You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用原生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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 10:30:52