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

在Squarespace的HTML头部注入jQuery代码时$函数无法执行

解决Squarespace中Head标签注入jQuery代码失效的问题

问题根源

你遇到的问题主要来自三个方面:

  • jQuery版本冲突:Squarespace自带jQuery环境,你在Head中额外加载的jQuery版本会与内置版本冲突,导致$无法正常调用。
  • 动态DOM渲染:Squarespace的预约模块内容是通过异步方式动态生成的,$(document).ready触发时,目标元素.appointment-type-name还未被渲染到页面中,选择器自然找不到元素。
  • 异步逻辑顺序错误:原代码中fetch请求是异步执行的,当调用removeRegex时,$(document).ready可能已经提前触发过,后续无法再捕获DOM就绪状态。

修复后的代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
// 解决jQuery版本冲突
var $ = jQuery.noConflict();

const token = "xxxxxxxxxxx";
var url = "https://ipinfo.io/json?token=" + token;
var userCountry = "";
const re = new RegExp('^IVA');

// 排除爬虫请求
if (!navigator.userAgent.match(/bot|spider/i)) {
    fetch(url)
        .then(res => res.json())
        .then(data => {
            userCountry = data.country;
            console.log('User is in: ' + userCountry);
            // 获取国家信息后,等待目标元素加载完成
            waitForAppointmentElements();
        })
}

// 监听目标元素是否加载完成
function waitForAppointmentElements() {
    // 检查元素是否已存在
    if ($(".appointment-type-name").length) {
        filterAppointmentTypes();
    } else {
        // 使用MutationObserver监听DOM变化,直到元素出现
        const observer = new MutationObserver((mutations) => {
            mutations.forEach(mutation => {
                if (mutation.addedNodes.length && $(".appointment-type-name").length) {
                    filterAppointmentTypes();
                    observer.disconnect(); // 找到元素后停止监听
                }
            });
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }
}

// 根据用户所在国家过滤预约类型
function filterAppointmentTypes() {
    $(".appointment-type-name").each(function() {
        const str = $(this).html();
        if (userCountry === "US") {
            // 美国用户仅保留以IVA开头的预约类型
            if (!str.match(re)) {
                $(this).closest('.select-item-box').hide();
            }
        } else {
            // 非美国用户隐藏以IVA开头的预约类型
            if (str.match(re)) {
                $(this).closest('.select-item-box').hide();
            }
        }
    });
}
</script>

关键修复点说明

  1. 处理jQuery冲突:通过jQuery.noConflict()重新绑定$,避免和Squarespace内置的jQuery版本冲突。
  2. 动态元素监听:用MutationObserver替代$(document).ready,确保目标元素渲染完成后再执行过滤逻辑。
  3. 调整异步逻辑顺序:在fetch请求获取到国家信息后,再启动元素监听,保证逻辑执行顺序正确。

内容的提问来源于stack exchange,提问作者o2mationnation

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:15:35