You
might 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 at the end of the src URL (with JavaScript) it needs to be written to the page. If the entire script element already exists then you can't simply use document.write(). However, if you have control over this script element then you perhaps could.
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....
<script language="JavaScript" src="http://example.com/test.php"></script>
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.