0

I have a script that replaces the HTML of a webpage if a certain query string is present. The script needs to be loaded AFTER the HTML, but must be run and update the HTML BEFORE the page finishes loading, in order for my external script to detect the content of the page. Is there a way to achieve this?

I made this timeline diagram to show when the events should happen.

  +--------------------------------+
  | |                              |
E |=• Page begins loading          |
v | |                              |
e |=====• Script runs and          |
n | |     website content changes  |
t | |                              |
  |=========• Page is loaded       |
  | |                              |
  +--------------------------------+
    ^   ^   ^      Time
    1   2   3

1 Answer 1

5

Include your script using the attribute defer.

<script src="./path/to/my/script.js" defer></script>

Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.