8

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)

    }
Pedro Ferreira
  • 301
  • 3
  • 11

1 Answers1

1

Try making the amendments below. the major change would be that you are checking the wrong variable before removing and adding the script. Check if the head contains a script and remove that. After that i made some changes to help the code be more readable and slightly drier.

const reloadScripts = (scrpSrc) => {
        console.log("Script loaded:  " + scrpSrc)
        const wpcf7 = { 
          "apiSettings": { 
            "root": "/wp-json\/contact-form-7\/v1", 
            "namespace": "contact-form-7\/v1" 
            } 
          };
        let head = document.querySelector('head'),
          headScript = head.querySelector('[src="='+ scrpSrc +'"]'),
          script = document.createElement('script');
         //checking if head already has a script
        if (headScript != undefined || headScript != null) {
            head.removeChild(headScript);
        }
        //then always do this piece. not DRY to have it inside and outside the if stmt
        script.src = scrpSrc;
        head.appendChild(script)
    }
tstrand66
  • 968
  • 7
  • 11
  • thanks, the only thing i didnt understand is why you are selecting a script tag on this line ` headScript = head.querySelector('script'),` because that will select the first script tag, and i dont want that :/ – Pedro Ferreira May 29 '20 at 17:47
  • @PedroFerreira you had it originally checking if the script variable that you had just defined was defined and if so then removing and readding. i assumed you wanted to remove the existing script tag and load the new one. if thats not the case please explain what your end goal is. – tstrand66 May 29 '20 at 18:13
  • The main thing is I wanna load a new script using the src I provide in the arguments, the script variable is that I have is the equivalent of the headScript they you created. The code that you wrote is fine, but the fact that you use query selector, selects the first script tag of the head and eliminates replaces it with the one we're creating – Pedro Ferreira May 29 '20 at 18:47
  • to make it short to you , i'm sorry for being so confusing. I am loading a new script tag , and the if tag just checks if the script i creatd already exists , so it doesnt load many scripts just like it ! – Pedro Ferreira May 29 '20 at 18:49
  • @PedroFerreira i have modified my answer to check if the headScript matches the passed src. if not it wont remove anything – tstrand66 May 29 '20 at 20:50