Reputation:
I have Load() function in an external file called cookieRedirect.js and I want to load that function before the <body> tag.
I used to load it like this:
<script type="text/javascript" src="cookieRedirect.js"></script>
</head>
<body onload=Load();>
But when I try this, it's not working:
<script type="text/javascript" src="cookieRedirect.js">
window.onload = Load();
</script>
</head>
<body>
Upvotes: 2
Views: 11819
Reputation: 70075
You can't include a src
attribute in your script
tag and inline JavaScript and expect them both to execute. If you do that, just the src
attribute will execute. See Degrading Script Tags.
You can split them into separate tags like so:
<script src="cookieRedirect.js">
</script>
<script>
window.onload='Load';
</script>
If you want Load()
to execute before the HTML document is loaded, you can do this:
<script src="cookieRedirect.js">
</script>
<script>
Load();
</script>
But do note that it will block parsing and rendering of your HTML until Load()
finishes. So if Load()
might take some time then this could have a negative impact on performance. This is unlikely to be a problem for a redirect script, but it is something to bear in mind generally.
Upvotes: 1
Reputation: 7880
If you want to load that function before page load, just add script code to the <head>
of the page, not in the body. window.onload
or onload=""
will execute your code only when the page was loaded, not before.
Do it this way:
<html>
<head>
<script src="cookieRedirect.js"></script>
<script>
Load();
</script>
<head>
<body>
</body>
</html>
Upvotes: 4