I have a javascript file like below which changes the innerHtml value of a header.
window.addEventListener("onload", function (e) {
console.log("Hit Javascript file");
if (this.document.getElementById('cardHeader')) {
document.getElementById('cardHeader').innerHTML = "Card Header Text";
}
});
The changes are noticeable for half a second and then it reverts back to its original value. I tried using defer incase the page wasn’t fully loaded. I also tried positioning the script tag inside the header, body and outside the body.
Inside my layout html this is where i’ve added the script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="~/" />
<link href='https://fonts.googleapis.com/css?family=Inter' rel='stylesheet'>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body>
@RenderBody()
<script src="https://mysitehere.azurewebsites.net/login-script.js" defer></script>
</body>
</html>
2
Answers
The problem here is that
onload
is an incorrect parameter to be used withwindow.addEventListener
:https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
Try
instead.
Alternatively,
In the first parameter of
addEventListener()
,"onload"
should just be"load"
: