Context:
I'm using barba js to make some page transitions on a wordpress website, and i have to load some scripts everytime the page changes, mainly some js/css files from a wordpress plugin so that ajax search works. I made a method that receives the script src/href and then adds the element to the head. the problem might be happenning from my poor code structure or from the library i dont know to be honest.
Problem:
The code only runs the first script i call, and as i said above, i dont know if its from my code or from the library !
Code:
At first i thought i needed some kinda of timeout for the code to work , so i did this
{
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"
}
},
This is the original Code (Without the timeouts) :
{
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"
}
},
Thanks in advance !
Edit: This is the method
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)
}