0

I have two JavaScript files. The first file, a.js, checks the screen size and loads file b.js if the screen size is less than 600 pixels. After the condition satisfies, I am calling a constructor function that is defined in file b.js. But it is giving me reference error that the function is not defined.

jQuery(document).ready(function() {
  jQuery(window).on("load", function() {
    const MinPx = 600;

    function downloadJS() {
      var x = document.createElement('script');
      x.type = 'text/javascript';
      x.src = '/js/b.js';
      document.body.appendChild(x);
    }
    if (jQuery(document).width() > MinPx) {
      downloadJS();
      new tpc("Homepage", jQuery("#a"));
    }
  });
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sunshine
  • 1
  • 2
  • The file `b.js` is not loaded yet. You need to place the constructor-calling code in the load callback. – Namaskar Sep 21 '17 at 16:46
  • but how do I do that? – sunshine Sep 21 '17 at 17:41
  • jQuery(document).ready(function() { jQuery(window).on("load", function() { const MinPx= 600; function downloadJS(){ var x=document.createElement('script'); x.type='text/javascript'; x.src='/js/b.js'; document.body.appendChild(x); } if (jQuery(document).width() > MinPx){ downloadJS(); new tpc("Homepage", jQuery("#a")); } }); }); – sunshine Sep 21 '17 at 17:43
  • Possible duplicate of [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – Namaskar Sep 21 '17 at 18:03
  • you just need to add `x.onload = function(){}` before the `document.body.appendChild(x)` line. – Namaskar Sep 21 '17 at 18:04

0 Answers0