当使用Barba.jS切换页面时,新页面中的脚本可能无法加载。这可能是因为旧页面的DOM元素依然存在于新页面的DOM中,所以脚本会被重复执行或未被执行。解决这个问题,可以在Barba.js的onLeave()
方法中,将旧页面中所有需要保留的脚本标记为data-barba-keep
,在新页面中再使用jQuery的$.getScript()
方法加载脚本。
代码示例:
barba.init({
transitions: [{
once() {
// This will only be called once, on the first page load
loadScripts()
},
leave() {
// Before leaving page
// Mark all scripts to keep
$('[data-barba-keep]').each(function() {
$(this).removeAttr('data-barba-keep')
this.id = '_' + this.id
})
},
enter() {
// After entering page
loadScripts()
}
}]
})
function loadScripts() {
$('script:not([data-barba-keep])').each(function() {
$.getScript(this.src)
})
}