3

I want to know how I can wait for one script to load before loading the next one. For example(and also actually load another page into the page completely):

<html> <script src = "script1"></script> <script src = "script2"></script> <script> $(document).ready( function() { $("#content1").load("index2.html"); }); </script> </html> 

So after loading script1 properly(and run all thats in there), I want to load script 2, and after that is loaded completelt, I want to load the document index2.html into this html-document.

What I have been trying so far is this but it is not working exactly as I want to.

File1: scriptOrderTest.html

<html> <div id ="content1"></div> <script src="js/jquery-3.2.1.min.js"></script> <script> var variable1 = undefined; $(document).ready( function() { $.ajax({ url: "script1.js", dataType: "script", success: () => { $.ajax({ url: "script2.js", dataType: "script", success: () =>{ // do the stuff you need $("#content1").load("index2.html"); } }); } }); }); </script> </html> 

File2: script1.js

console.log("Starting script 1"); function revealTime(){ console.log("Oh, I just wasted 5 seconds of my life") } //This script is just wasting time setTimeout(revealTime,5000); 

File3: script2.js

console.log("Starting script 2"); function revealTime(){ console.log("Oh, I just wasted 5 seconds of my life AGAIN") ; variable1 = "Pizza"; } //This script is just wasting time setTimeout(revealTime,5000); 

File4: index2.html

<html> <script src="js/jquery-3.2.1.min.js"></script> <script> document.write("The variable is:"+variable1); </script> </html> 

Firstly, So the goal is to wait for the scripts to finish so that the variable can get a value before writing it on the page. This is not the case with the code above.

1
  • That's exactly what the code above will do. What issue are you having with it? Commented Mar 3, 2018 at 9:09

2 Answers 2

2

You could resolve this issue by using Promise and chain actions together.

if you make a function that add the script and then tell's you when it is done.

something like:

function addScript(url){ return new Promise((resolve, reject) => { console.log("Download", url); var script = document.createElement("script") script.type = "text/javascript"; script.onload = function(){ console.log(`Download done (${url})`); resolve(1); }; script.src = url; document.getElementsByTagName("head")[0].appendChild(script); }); } 

And define all the scripts you need, i just made an useless example with vue.

const scripts = [ "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js", "https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.1/vue-router.js" ]; 

Sequential

What you asked for in the question - download on at the time, delaying downloading the next script until first one is done.

const tasks = scripts[Symbol.iterator](); function addAllScripts(callback){ const url = tasks.next().value; if(url){ addScript(url).then( () => { addAllScripts(callback); } ); }else{ callback(); } }; addAllScripts(() => { console.log("Ready"); new Vue({ el: '#app', template: '<p>hello world</p>' }); }); 

function addScript(url){	return new Promise((resolve, reject) => {	console.log("Download", url);	var script = document.createElement("script") script.type = "text/javascript"; script.onload = function(){	console.log(`Download done (${url})`); resolve(1); }; script.src = url; document.getElementsByTagName("head")[0].appendChild(script); }); } const scripts = [ "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js", "https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.1/vue-router.js" ]; const tasks = scripts[Symbol.iterator](); function addAllScripts(callback){	const url = tasks.next().value; if(url){ addScript(url).then( () => { addAllScripts(callback); } ); }else{ callback(); } }; addAllScripts(() => {	console.log("Ready"); new Vue({ el: '#app', template: '<p>hello world</p>' }); });
<div id="app"></div>

Parallel

Optimal solution, faster execution - add all scripts at once, and wait until all are done

const tasks = scripts.map(addScript); Promise.all( tasks ) .then(function(){ console.log("Ready"); new Vue({ el: '#app', template: '<p>hello world</p>' }); }); 

function addScript(url){	return new Promise((resolve, reject) => {	console.log("Download", url);	var script = document.createElement("script") script.type = "text/javascript"; script.onload = function(){	console.log(`Download done (${url})`); resolve(1); }; script.src = url; document.getElementsByTagName("head")[0].appendChild(script); }); } const scripts = [ "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js", "https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.1/vue-router.js" ]; const tasks = scripts.map(addScript); Promise.all( tasks ) .then(function(){ console.log("Ready"); new Vue({ el: '#app', template: '<p>hello world</p>' });	}); 
<div id="app"></div>

Sign up to request clarification or add additional context in comments.

7 Comments

You have written very nice code, I just don't understand it. Maybe I am not enough experienced as a java developer yet ...
javascript* ;) - what part do you not understand, then i can try and clear it up a bit.
The code about the SEQUENTIAL solution code snippet. Maybe you could write some comments on each line about what is happening. I am also unsure of the flow of the code execution, where does it start and end and so on.
I mean, you use like promises and callbacks and the object Vue() i don't have a clue about. Everything is stuff that I don't know how to use yet properly : p
Ah yes sure, well you dont need the Vue stuff, was just as the scripts i loaded was vue, so it was just to demo the script. but you can see some comments here: jsfiddle.net/Lke59208/10
|
1

Put this in document.ready:

$.ajax({ url: url1, dataType: "script", success: () => { $.ajax({ url: url2, dataType: "script", success: () =>{ // do the stuff you need } }); } }); 

5 Comments

I added some info to my comment, can you check if I understood you correctly maybe?
It is not working exactly as I wanted, firstly, script 2 is not waiting for script 1 to finish its stuff before being loaded into the page. I think i will paste the code in my files to show what I have done.
If you put setTimeout, then yes, second script starts loading before script1 setTimeout function is invoked in 5 seconds
Because the problem is, It don't have control over what happens in script1. It is another persons work which I cannot change. But I don't want to load my stuff before his scripts have executed everything properly.
In that case you need to wait till all setTimeout staff is done in script1. Where us no other way if you cannot change script1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.