在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>
关键修复点说明
- 处理jQuery冲突:通过
jQuery.noConflict()重新绑定$,避免和Squarespace内置的jQuery版本冲突。 - 动态元素监听:用MutationObserver替代
$(document).ready,确保目标元素渲染完成后再执行过滤逻辑。 - 调整异步逻辑顺序:在fetch请求获取到国家信息后,再启动元素监听,保证逻辑执行顺序正确。
内容的提问来源于stack exchange,提问作者o2mationnation
相关产品推荐
相关产品推荐

