1

I have a js file which I want to load after Jquery deffered function. Thing is that I am bring data in my getData function and then inject string into the DOM. After that js file will initialize that code. That is the reason I want to call js file after my code runs

How can I do that

Below is my code.

jQuery function decalaration

function getData(url) {
  return $.ajax({
    url: url,
    method: 'GET',
    headers: {
      Accept: 'application/json; odata=verbose',
    },
  })
}

function call

getData(url).then(function(data){

});

Now I want to call jQuery file after finish of then function.

<script src="file.js"></script>
Milind
  • 1,687
  • 3
  • 26
  • 56

1 Answers1

1

You need to use Promise/await way, Since you need to write js file after execute something, so that you can let js file wait until your code finished, and then write your new js file to body....check this example:

/* MEthod used to write js to body script */
function addJsFileToBody(jsSrc)
{
    var script = document.createElement("script");
        script.src = jsSrc;
        document.getElementsByTagName("body")[0].appendChild(script);
}

var promise1 = new Promise(function(resolve, reject) {
  $.ajax({
    url: url,
    method: 'GET',
    headers: {
      Accept: 'application/json; odata=verbose',
    },
    complete: function(data) {
      resolve(data);
    }
  })
});

promise1.then(function(value) {
  addJsFileToBody('file.js');
});

Reference and example: Promise and await

Anees Hikmat Abu Hmiad
  • 2,589
  • 1
  • 16
  • 33