Can't run script after another script is completely loaded

Tried with callbacks, async await and nothing works :confused:
Basically I have inside a conditional the following code

var CarouselScript = document.createElement("script");
          CarouselScript.src = "https://wlada.github.io/vue-carousel-3d/js/carousel-3d.umd.js";
          CarouselScript.async = false;
          body.appendChild(CarouselScript);

          //

          setTimeout(function(){
          var VueInitScript = document.createElement("script");
          VueInitScript.async = false;
          VueInitScript.src = "<?php bloginfo('template_url'); ?>/vue-init.js";
          body.appendChild(VueInitScript);

          }, 450);

And the idea is to replace the setimeout method, so that once CarouselScript is loaded, then it should load VueInitScript, because the first is a dependency of the second one.

And here’s what I tried:

  1. Callback
function loadScript(callback){
            //var head = document.getElementsByTagName('head')[0];
            var CarouselScript = document.createElement("script");
            CarouselScript.type = 'text/javascript';
            CarouselScript.src = "https://wlada.github.io/vue-carousel-3d/js/carousel-3d.umd.js";
            CarouselScript.onreadystatechange = callback();
            CarouselScript.onload = callback();
            body.appendChild(CarouselScript);
        }

        function MiArchivoCargado(){
             var VueInitScript = document.createElement("script");
             VueInitScript.type = 'text/javascript';
             VueInitScript.src = "<?php bloginfo('template_url'); ?>/vue-init.js";
             VueInitScript.async = false;
             body.appendChild(VueInitScript);
        }
        loadScript(MiArchivoCargado);
  1. Async await
const CarouselScript = ()=>{
           var CarouselScript = document.createElement("script");
           CarouselScript.src = "https://wlada.github.io/vue-carousel-3d/js/carousel-3d.umd.js";
           CarouselScript.async = false;
           body.appendChild(CarouselScript);
          }

          const VueInitScript = ()=>{
            var VueInitScript = document.createElement("script");
            VueInitScript.async = false;
            VueInitScript.src = "<?php bloginfo('template_url'); ?>/vue-init.js";
            body.appendChild(VueInitScript);
          }

          async function asyncLlamado(){
            await CarouselScript(); // then task2 want start until the task1 finishes
            VueInitScript();
          };

          asyncLlamado();

Do note there are 3 scripsts in total, so setting the last two scripts have to be appended to body, since there’s already one in the head.

Hello!

Why don’t you use events? Make the body (or any tag) dispatch an event once the required script is fully loaded:

// first.js

// assume you do the work you require here,
// and once you're done:
document.querySelector('body').dispatchEvent(new Event('firstLoaded'));

Then load the carousel:

// carousel.js
document.querySelector('body').addEventListener('firstLoaded', () => {
  // do the carousel work here or call the function to do it
  // and once it's done:
  document.querySelector('body')
.dispatchEvent(new Event('carouselLoaded'));
});

And finally, call the vue init script:

// Your vue 
document.querySelector('body')
.addEventListener('carouselLoaded', () => VueInitScript);

With this method you would be loading all the scripts at once, not after the page has been loaded.

Take a look at this: https://replit.com/@skaparate/UsingEvents

By the way, using any of the methods you used, what errors did you find (if any)? Did you check the developer tools console?

Thanks so much!!
No errors on the console :confused: … but I’m only getting with console.log the “1” of the first script, so the second and third scripts may not be running… Current code:

var head = document.getElementsByTagName('head')[0];
          var body = document.getElementsByTagName('body')[0];          
            //first script
            var VueScript = document.createElement("script");
            VueScript.src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.7/vue.js";
            //VueScript.async = false;            
            head.appendChild(VueScript);
            document.querySelector('body').dispatchEvent(new Event('firstLoaded'));
            console.log("1")          

       // second script
        body.addEventListener('firstLoaded', function () {
            var CarouselScript = document.createElement("script");
            CarouselScript.src = "https://wlada.github.io/vue-carousel-3d/js/carousel-3d.umd.js";
            //CarouselScript.async = false;
            body.appendChild(CarouselScript);
            body.dispatchEvent(new Event('carouselLoaded'));
             console.log("2")
        });
        
        //third script
        body.addEventListener('carouselLoaded', function () {
              var VueInitScript = document.createElement("script");
              //VueInitScript.async = false;
              VueInitScript.src = "<?php bloginfo('template_url'); ?>/vue-init.js";
              body.appendChild(VueInitScript);
             console.log("3")
        });

But that won’t work quite well either, since you won’t be sure that the scripts are truly loaded if the events are fired outside the initialization scripts.

Why do you need to load the Vue carousel (which I assume it’s a vue component, right?) from github? Why don’t you include it within your vue app using NPM/Yarn? (I should have asked this first xD :man_facepalming:t4:)

Because I don’t know yet much of JS backend I suppose… and tried to do this that way.

Mmm and what can I do without editing the script files? If I understood correctly it would work if I call the next script from within the previous one.

The first code you posted should be working, but I can’t know why it isn’t without debugging all the involved code. You may be having CORS problems or something else preventing the correct load of the scripts.

You can check the console to make sure every script is loaded: the Network tab will help you see which files have been downloaded (every HTML page, JavaScript file, image and any kind of request).

Add debugging messages and/or use a debugger to find out the problem. For instance: Debugging in VS Code — Vue.js

I hope it helps :slight_smile:.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.