add script dynamically to DOM before other scripts are executed

Viewed 306

I do a simple check if js file exists. If not, I try to load it dynamically before other scripts from bottom of a page are loaded. Is it possible to do? Here is fiddle where bottom script is executed before thus giving errors. https://jsfiddle.net/vnfxus56/1/

thank you.

<div id="top">top</div>
<script>
  doesFileExist('https://ajax.googleapis.com/ajax/libs/nonexistingfile.js');

  function doesFileExist(urlToFile) {
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send();

    if (xhr.status == "404") {
      console.log("File doesn't exist");
      var script = document.createElement('script')
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js'
      document.head.append(script)

      return false;
    } else {
      console.log("File exists");
      return true;
    }
  }

</script>



<script>
//this is printed out of a variable as a bunch of inline jquery code
$("#top").fadeOut();
</script>
1 Answers

below I posted the code that could await until the "xhr" request is finished. I used the "async functions" concept in javascript that you can read more about it here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

function afterLoad() {
    console.log('DOM fully loaded and parsed');
    $("#top").fadeOut();
}
#top { 
    background-color: green; 
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>xhr</title>
    <link rel="stylesheet" href="style.css">
</head>
<body onload="afterLoad()">
  <!-- using "onload" method is necessary to run the script after finishing "xhr" -->
   
<div id="top">top</div>
<script>

let urlToFile = 'https://ajax.googleapis.com/ajax/libs/nonexistingfile.js';

  function doesFileExist(urlToFile) {
      
    return new Promise(resolve => {
        
        var xhr = new XMLHttpRequest();
        xhr.open('HEAD', urlToFile, false);
        xhr.send();

    if (xhr.status == "404") {
      console.log("File doesn't exist");
      var script = document.createElement('script');
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js';
        script.setAttribute("async", "");
        console.log(script);
      document.body.append(script);
        
        // your custom script file
        var script2 = document.createElement('script');
      script2.src = 'myscript.js'; // define the address of your javascript file.
      script2.setAttribute("async", "");
      document.body.append(script2);

      resolve(false);
        
    } else {
      console.log("File exists");
      resolve(true);
    }
       

    });
      
    
  }

  async function asyncCall(urlToFile) {
        console.log('starting');
        const result = await doesFileExist(urlToFile);
        console.log(result);
        console.log("finished");
    }
    
    asyncCall(urlToFile);
</script>



    
</body>
</html>

I think it is useful to mention that I changed your code from two "script" tags to only "one" and used "two" functions in it. one of them works on "xhr" request and adding script tags, and the other forces the code to wait until the xhr request is finished. I added "$("#top").fadeOut();" part of your code to a separate script code that is in the same directory and appended the script tag in first function.

Related