be able to do this but may be not the way you are expecting. You don't give enough detail in order to give a sufficient answer.
In order to get the value of ref
If the script element already exists without the 'r' url param as the page loads then it is going to make a request for this document before you've had a chance to append the ref value - this may not work for you?
Ideally, either you need to have control over what is written to the page (the document.write() I assume?), or the entire script element should not appear at all when the document is created.
What exactly is written out with document.write() in the 'bottom script'...? Does it include something like....
If this can not be altered before
it is written to the page then you cannot prevent the request for test.php without the 'r' url param. However, you could discard this initial request (if you have control over test.php) and use the code from my first answer to add the 'r' param to the request via the DOM. A second request is then made for test.php, this time with the 'r' parameter. But I'm making assumptions about how your scripts are hanging together.