2

I want to load a script that loads another script based on condition and this script is adding a variable to the global window.

<head>
    <script src="load-something.js"></script>
    <script>conosle.log(window.someVariable)</script>
</head>

load-something.js

function loadScript( path ) {
  const head = document.getElementsByTagName('head')[0];
  const script = document.createElement('script');
  script.src = path;
  head.append(script);
}

if(condition) {
  loadScript('pathToJsFile.js');
}

pathToJsFile.js

window.someVariable = ...

My problem is that someVariable is undefined. Is it possible to force the script to block?

undefined
  • 6,366
  • 12
  • 46
  • 90
  • It will be undefined on that point, try to console.log someVariable in pathToJsFile.js and you will see that it exists when it's loaded. Probably you have to do that in async way, or fire event from pathToJsFile.js and declare listener for that load event, after which you will be able to use this variable. Also there is a `setTimeout()` workaround but it isn't recommended. try to check for `typeof window.someVariable == 'undefined'` before calling it – Maksym Shevchenko Mar 15 '18 at 07:59
  • I need it to be available in the next script tag. This is my question. I need to block. – undefined Mar 15 '18 at 08:01
  • well in this case you can simply get your second script tag `` and move its code to a file, and load this script right after you are loading pathToJsFile.js depending on a condition – Maksym Shevchenko Mar 15 '18 at 08:04
  • I need to access it from other scripts that l load. – undefined Mar 15 '18 at 08:07

3 Answers3

0

How about this?

<!doctype html>
<html lang="en">
  <head>
    <title>Hello, world!</title>
<script>
    var condition = true;
    var data;
    function loadDoc() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
         data = this.responseText;
        alert(data);
        }
      };
      xhttp.open("GET", "test.json", true);
      xhttp.send();
    }
    if (condition) {
        loadDoc();
    }
</script>
  </head>
  <body>
  </body>
</html>
0

You can use onload property of DOM element, more clean example can be found here

For sure you can't expect that "window.someVariable" will be defined in the next block you can read about loading/executing order in this answer.

As a solution you can add something like "isAllLoadedd" to your 'load-something.js':

let pathsToLoad = [],
    leftToLoad = 0;
function loadScript( path ) {
  let head = document.getElementsByTagName('head')[0];
  let script = document.createElement('script');
  script.src = path;
  script.onload = () => leftToLoad--; 
  head.append(script);
}

if(condition) {
   pathsToLoad.push('pathToJsFile.js')
}
leftToLoad = pathsToLoad.length;
 for (let file of pathsToLoad)
   loadScript(file);

function isAllLoaded() {
   return !!leftToLoad.length;
}

And then in your block with "someVariable":

 let _int = setInterval(function() {
    if (isAllLoaded()) {
      console.log(someVariable);
      clearInterval(_int);
    } 
}, 100)

But in your particular case, you can all leave as is, and just use your someVariable after it will be defined :), but in any case you will need to wait until your dependency will be loaded.

2oppin
  • 1,941
  • 20
  • 33
-1

Here is the code to add code to head dynamically

#linking style sheet

var linkElement=document.createElement('link');
linkElement.href='resources/css/animate.min.css';
linkElement.rel='stylesheet';

# linking script
var scriptElement = document.createElement('script');
scriptElement.src = "resources/js/check_session.js";

# add to head tag -> header
document.getElementsByTagName('head')[0].appendChild(linkElement);
document.getElementsByTagName('head')[0].appendChild(scriptElement);
Saurabh Pandey
  • 519
  • 2
  • 15