Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make script execute once the first script is loaded

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

window.addEventListener('load', function() {
    Framework.store('name', 'Joe');
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading