1

My script looks like this:

<script>
    var queryString = window.location.search;
    var pos = queryString.indexOf("?refer=");
    var referEmail = queryString.substring(pos+7);
    document.getElementById("referral-code").value = referEmail;
</script>

And the HTML codes look like this:

<form action="/" method="POST">
    <label for="referral-code">Referrer's code (hidden): </label>
    <input type="text" name="referral_code" id="referral-code"/>
    <br/>
    <label for="me-email">My Email: </label>
    <input type="text" name="self_email" id="me-email"/>
    <br/>
    <input type="submit" value="Step Inside" />
</form>

I think it may be cleaner to put the <script> tag in <head>. However, I am not sure whether the script will wait to be executed until the DOM in <body> is processed. If not, will document.getElementById("referral-code") returns undefined?

Does anyone have ideas about whether a script in <head> will wait to be executed until the whole HTML is loaded? And should I put the DOM manipulating script in <head> or before the closing </body>?

Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237
  • Script in the head section is executed before the body has been parsed. But you can put your code inside a function that you assign as an `onload` handler, or `DOMReady` handler, and *then* that function will be executed *after* the body has been parsed. (Note that `getElementById()` never returns `undefined`: if a matching element isn't found it returns `null`.) – nnnnnn Sep 05 '15 at 03:17
  • At the end of body, if you want to put in head see.http://stackoverflow.com/questions/29772994/how-to-have-a-script-in-the-head-add-script-at-the-end-of-the-body/29773084#29773084 – Tushar Sep 05 '15 at 03:17
  • Possible duplicate of http://stackoverflow.com/questions/29772994/how-to-have-a-script-in-the-head-add-script-at-the-end-of-the-body/29773084 – Tushar Sep 05 '15 at 03:18

2 Answers2

0

if you want to put in head then make sure you put it in

$(document).ready(function(){

});

otherwise you can put it after the DOM completion (just right before </body> )

maddygoround
  • 2,145
  • 2
  • 20
  • 32
0

If placed in the header the script will execute before DOM loads and won't add the referal code to the input (as it doesn't yet exist).

I'd suggest putting it before the tag.

$(document).ready(function(){}); vs script at the bottom of page has some more information on some of the pros/cons/differences of script tag/file location.

Community
  • 1
  • 1
Brian
  • 2,822
  • 1
  • 16
  • 19