Odd issues with profile parameters
The context:
I have two user groups(beta1 and beta2) in AEM. When a user logs into the website, I capture whether they are in the beta1 or beta2 groups in a JS variable that is placed just before the launch script, so that when the delivery request is sent, I can utilize this value as a profile parameter for targeting. The following is the launch rule:

Where the custom code is:
function targetPageParams() {
var group = userGroup; //userGroup variable is set to beta1/beta2 just before the launch script
return "profile.userGroup="+group;
}
The issue:
1. The profile parameters are not sent to the target on the very first page load. Target is giving the default experience since the request field for the profile parameters is empty. I tried replacing the custom code with a hardcoded value along but got the same result. The profile parameters are not being sent as anticipated when the user logs into the website for the first time/incognito.
Tried a console.log as well inside targetPageParams(). For the first page load after sign in, targetPageParams is not getting called but on a subsequent page reload the function is getting called and is consoling out.
function targetPageParams() {
var group = userGroup;
console.log(group);
return "profile.userGroup="+group+"&profile.testGroup=test";
}
2. When I soft refresh(normal reload) the page (Ctrl+R), the profile parameters function as expected and the right experience is given, indicating that I just needed to reload the page once for the target to work. When I examine the delivery request after a hard reload (Ctrl+Shift+R), the profile params are missing, yet target is providing the right experience for the page(The response token does contains this value but no profile params are being send - Does this got anything with Experience Cloud Visitor ID and target is working based on that?). And I have to refresh the website multiple times to see the profile parameters in the delivery request, but the experience remains intact after each reload (normal or hard), indicating that the right experience is being delivered.
Both these issues appear to be strange and couldn't figure out why.
Update: I did try removing the custom code from the launch rule and placed it in the page header just before the launch script and that is working fine. The targetPageParams() is getting called every time irrespective of any cases and the right experience is being delivered. However, writing and updating the code in the page header doesn't appear to be a best practice as any additional change in params require a code change in AEM and a build.