语境:
我正在使用 barba js 在 wordpress 网站上进行一些页面转换,每次页面更改时我都必须加载一些脚本,主要是来自 wordpress 插件的一些 js/css 文件,以便 ajax 搜索工作。我做了一个接收脚本 src/href 然后将元素添加到头部的方法。问题可能出在我糟糕的代码结构或我不知道老实说的库中。
问题:
该代码只运行我调用的第一个脚本,正如我上面所说,我不知道它是来自我的代码还是来自库!
代码:
起初我以为我需要一些超时才能使代码工作,所以我这样做了
{
namespace: 'product',
beforeEnter(data) {
//loads styles
setTimeout(reloadStyles('ivory-search-styles-css', 'wp-content/plugins/add-search-to-menu/public/css/ivory-search.css?ver=4.4.7'), 500)
//loads javascript files.
setTimeout(reloadScripts('wp-content/plugins/add-search-to-menu/public/js/ivory-ajax-search.js?ver=4.4.7'), 800)
setTimeout(reloadScripts('/wp-content/plugins/add-search-to-menu/public/js/ivory-search.js?ver=4.4.7'), 1000)
setTimeout(reloadScripts('/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=5.1.7'), 1200)
searchTranslations()
// refresh breadcrumbs
let documentAjax = (new DOMParser()).parseFromString(data.next.html, 'text/html');
let breadcrumbsAjax = documentAjax.querySelector('.breadcrumbs')
let breadcrumbs = document.querySelector('.breadcrumbs')
breadcrumbs.innerHTML = breadcrumbsAjax.innerHTML;
logoPath.style.fill = "black"
}
},
这是原始代码(没有超时):
{
namespace: 'product',
beforeEnter(data) {
reloadStyles('ivory-search-styles-css', '/wp-content/plugins/add-search-to-menu/public/css/ivory-search.css?ver=4.4.7')
reloadScripts('/wp-content/plugins/add-search-to-menu/public/js/ivory-ajax-search.js?ver=4.4.7')
reloadScripts('/wp-content/plugins/add-search-to-menu/public/js/ivory-search.js?ver=4.4.7')
reloadScripts('/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=5.1.7')
searchTranslations()
// refresh breadcrumbs
let documentAjax = (new DOMParser()).parseFromString(next.html, 'text/html');
let breadcrumbsAjax = documentAjax.querySelector('.breadcrumbs')
let breadcrumbs = document.querySelector('.breadcrumbs')
breadcrumbs.innerHTML = breadcrumbsAjax.innerHTML;
logoPath.style.fill = "black"
}
},
提前致谢 !
编辑:这是方法
const reloadScripts = (scrpSrc) => {
console.log("Script loaded: " + scrpSrc)
var wpcf7 = { "apiSettings": { "root": "/wp-json\/contact-form-7\/v1", "namespace": "contact-form-7\/v1" } };
let head = document.getElementsByTagName('head')[0]
let script = document.createElement('script')
script.src = scrpSrc;
if (script != undefined || script != null) {
head.removeChild(script)
head.appendChild(script)
}
else head.appendChild(script)
}