Event load inside event load?

Asked

Viewed 50 times

1

I need the first load to solve the autoload problem of the scripts I do with php where I cannot define the order in which they will be loaded, and after that I need to load another load. You can use a load event within another load event?

INDEX.HTML

<html>
  <head>
    ...
  </head>
  <body>
    ...
    <?php
      $scripts = dir("js");
      while ($script = $scripts->read()) if ($scripts != "." && $scripts != "..") echo "<script src='js/{$script}'></script>";
    ?>
  </body>
</html>

There I have the letter.js, funcoes.js, script.js and text.js files. letter and text are classes, functions have a lot of functions that I use in the program and the script depends on those files are already read to work.

SCRIPT.JS

const cnv = document.getElementById("canvas");
cosnt ctx = cnv.getContext("2d");
const imgs = [];
for (let i = 0; i < 10; i++) {
  (imgs[i] = new Image()).src = `img/imagem${i}.png`;
}
window.onload = () => {
    // executa o resto
}

  • Can you show the code you have? so we can find another solution that is more suitable

  • Okay, I’ll edit it out.

1 answer

1


Generates an array with these scripts and then uploads it to Javascript like this:

<script>
const scripts = [
<?php
  $scripts = dir("js");
  while ($script = $scripts->read()) if ($scripts != "." && $scripts != "..") echo $script.",";
?>
];


function loadScript(src, done) {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'ajaxnotxt.txt';
  script.onload = done
  document.body.appendChild(script);
}

function carregarScripts(scripts, done) {
  let carregados = 0;
  scripts.forEach((script) => {
    loadScript(script, () => {
      carregados++;
      if (carregados == scripts.length) done();
    });
  });
}

carregarScripts(scripts, () => {
  // aqui todos os scripts estão carregados
  const cnv = document.getElementById("canvas");
  const ctx = cnv.getContext("2d");
  const imgs = [];
  for (let i = 0; i < 10; i++) {
    (imgs[i] = new Image()).src = `img/imagem${i}.png`;
  }

  // executa o resto

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.