<script src="./config.js"></script>
<script>
// config.js 暴露一个全局 config 对象
console.log(config)
</script>
因为浏览器缓存问题, 所以想动态引入 config
让浏览器不走缓存
但问题是 document.write
和 document.createElement
加载的js都是 异步加载
的, 这样后面的引用会报错
请问如何让他 同步动态
加载呢? 除了用 script
标签的加载完成事件来处理 callback
你错了。document.write
是同步的.
当时一般来说这方案不科学。可以用其他的方案
- 版本号。杨周龙的方案
- 设置不缓存。lansun的方案
- requirejs。类似于三楼说的方案把。只不过是兼容性的方案,异步加载资源,资源满足才执行
- 改造成不相互依赖的。自然也就没有这个问题了。
<script>
console.log(1, typeof window.Vue)
</script>
<script src="/uploads/allimg/210506/0Z10C408-1.jpg"></script>
<script>
console.log(2, typeof window.Vue)
</script>
<script>
console.log(3, typeof window.jQuery)
</script>
<script>
document.write('<script src="/uploads/allimg/210506/0Z10B0N-2.jpg"><\/script>')
</script>
<script>
console.log(4, typeof window.jQuery)
</script>
###我一般是这么做的
loadConfig.js
// ====页面动态加载config.js====
var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement
var oscript = document.createElement('script')
oscript.src = '*****/config.js'
head.insertBefore(oscript, head.firstChild)
// 获取config.js
function getConfig() {
var config
try {
config = getConfig()
if (!config && document.readyState !== 'complete') {
alert('config.js还没加载好,请稍后再试!')
return
}
return config
} catch (err) {
console.log('加载config.js失败')
}
}
export { getConfig }
其他页面使用
import { getConfig } from '**/loadConfig.js'
...
....
const config = getConfig()
###服务端设置 Response Header
Cache-Control: no-store
###1.要么像楼上修改config.js response 返回headers
2.在加载路径上面加get参数
<script src="./config.js?=xxxx"></script>
3.改一下编程方式,先创建一个confg全局变量,订阅这个变量加载数据完成触发后面的程序初始化等,可以通过proxy代理方式实现
###https://developer.mozilla.org...
在type="module"的script标签里可以使用require,就能同步动态引入js文件了
###上面都说了好几个思路了,再补充一个,
document.createElement
,创建标签时设置一下 onload
事件的回调。然后再 onload 里面取 config。
这样,再 createElement 时就可以添加随机参数的形式来避免缓存了。
###其实你说的我有点没太明白,就是document.createElement
异步加载,再调用的时候会出错 , 正常情况下不会出错的才是吧, 是不是你在异步加载的时候,脚本加载的顺序有问题? 如果是加载顺序的问题 你可以看看这篇文章 https://blog.csdn.net/csder_x...
同时不建议同步加载非必要js脚本,这样会拖慢页面的加载速度