2

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

2 Answers2

4

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John
  • 7,500
  • 16
  • 62
  • 95
  • 1
    +1 for getting correctly inferring the user's exact need from context, which I...uh...failed to do initially. :-) – Trott Jul 22 '12 at 17:51
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Trott
  • 66,479
  • 23
  • 173
  • 212
  • he wants to load the "Load();" function "before body tag", but window.onload will load the function only when all content was loaded. – John Jul 22 '12 at 17:41
  • It is not entirely clear what "load before the body tag" means. I interpreted it as "have all that JS stuff loaded into my HTML document before the body tag shows up". You have inferred that it meant "execute before the load event", and that is a perfectly valid interpretation, and judging from the OPs reaction, the correct one. – Trott Jul 22 '12 at 17:45
  • I've added the "execute right away, don't wait for Load()" option. Go team. Rah rah. Etc. – Trott Jul 22 '12 at 17:50