Load a scrip tag after another script tag has been loaded

Asked

Viewed 62 times

0

I want to load a script tag only when the other one is FULLY loaded.

Example:

<script type="text/javascript" src="js/scriptUm.js"></script>  
<script type="text/javascript" src="js/scriptDois.js"></script>

I want scriptDois to load only after scriptum has loaded COMPLETELY.

I have tried some ways but all were related to page loading, I would like a way that is related to loading another script.

  • 2

    The way you put it, they’re already loaded in sequence.

  • Maybe this question will help you https://answall.com/questions/138892/%C3%89-poss%C3%Advel-include-one-file-javascript-in-another-file-javascript

  • @bfavaretto Correct me if I’m wrong, they are actually executed in sequence, however the scriptDois does not run independently of the scriptum having finished its execution completely.

  • 1

    The second executes when it finishes the execution of the first. Unless you are firing asynchronous operations (timers, ajax) and want to load the second at the end of these operations. In this case the load will depend on what the code of the first script is like. Maybe this helps you: https://answall.com/q/14544

2 answers

0


uses script1 as a key to start script2

function script1() {
    //codigos que quer que seja executado primeiro
    return script1(true);
}

function script2(keyRun) {
    if(keyRun){
        //o que quiser que execute
    }
}

Thus script2 will only run when script1 is executed.

If you are using asynchronous functions in script1, you will have to treat it with Promise, more or less like this:

async function script1() {
    myCode = (resolve, reject) => {
        //vou usar o fetch como exemplo de função assincrona
        fetch(url)
            .then((html) => {resolve(script2(true))})
            .catch((error) => reject(console.error(error)));
    }
    return await new Promise(myCode);
}

function script2(keyRun) {
    if(keyRun){
        //o que quiser que execute
    }
}

In such case, if an error occurs script2 will not be executed, but this can be easily solved with due error handling

0

You can use the Defer attribute of the script tag.

<script defer type="text/javascript" src="js/scriptUm.js"></script>  
<script defer type="text/javascript" src="js/scriptDois.js"></script>

This way the loading of the script passes from the default (fetch followed by the execution), which pauses the loading of the HTML, to the asynchronous fetch and sequence execution after the loading of the HTML according to the call order of the files.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.