Home > Software engineering >  How to make script execute once the first script is loaded
How to make script execute once the first script is loaded

Time:11-23

I'm trying to make a web framework and one feature will be a key-value state management tool. I need the second <script> tag to only run after ./script.js loads in.
index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./framework.js"></script>
</head>
<body>
  <p f-text="name"></p>
  <script>
    Framework.store('name', 'Joe');
  </script>
</body>
</html>

framework.js:

document.querySelectorAll('*').forEach((element) => {
  if (element.hasAttribute('f-text')) {
    const textValue = element.getAttribute('f-text');

    const key = window.fStore.find((x) => x.key === textValue);

    element.innerHTML = key.value;
  }
});

window.Framework = {
  store: (key, value?) => {
    if (!value) {
      const foundKey = window.fStore.find((x) => x.key === key);

      return foundKey.value;
    }

    window.fStore = [...window.fStore, { key: key, value: value }];
  }
}

Error:

SyntaxError: Unexpected token ')'
    at /framework.js:12:22
ReferenceError: Framework is not defined
    at /:12:5

CodePudding user response:

You need to wait that your script is loaded, you can use this

window.addEventListener('load', function() {
    Framework.store('name', 'Joe');
})
  • Related