动态加载新版Google自动补全脚本报错:c未定义
解决新版Google Places自动补全脚本动态加载的变量解析错误
问题原因
你用外层模板字符串设置script.textContent时,新版脚本内部的${c}被外层模板引擎当成变量解析,导致未定义错误。
可行解决方案
直接使用普通字符串赋值
放弃模板字符串,用单引号包裹脚本内容,这样内部的${}不会被解析。示例代码:const script = document.createElement('script'); script.textContent = '(function(){/* 新版Google Places脚本内容,${c}保持原样 */})()'; document.head.appendChild(script);转义内部模板标记
如果必须使用模板字符串,把脚本里的${}转义为\${},阻止外层解析。示例代码:const script = document.createElement('script'); script.textContent = `(function(){ // 转义后的内部模板字符串 const targetStr = \`example \${c}\`; // 其余脚本逻辑 })()`; document.head.appendChild(script);通过Blob对象加载(推荐)
把脚本内容转为Blob,再生成临时URL作为script的src加载,完全规避模板解析冲突,和旧版加载方式逻辑一致。示例代码:const scriptContent = '(function(){/* 新版Google Places脚本完整内容 */})()'; const blob = new Blob([scriptContent], { type: 'text/javascript' }); const script = document.createElement('script'); script.src = URL.createObjectURL(blob); document.head.appendChild(script); // 加载完成后释放临时URL资源 script.onload = () => URL.revokeObjectURL(script.src);
内容的提问来源于stack exchange,提问作者temple
相关产品推荐
相关产品推荐

