[SalesForce] Use Apex Controller variable into javascript in Static Resource

I have created a vf page and added some javascript into that vf page which is using controller variable :

<apex:page controller="webstore">
<script>
    var username = '{!username}'
</script>
</apex:page>

It was working fine till the script was on vf page. Now, I have removed script from the vf page and created a static resource and have placed script into that. I have added that static resource into my page but now that script is not working. The script has been unable to identify that controller variable. It seems that controller variable doesn't work in this way. Is this a problem or I am missing something ?

Best Answer

Only Visualforce page (and component) files go through the binding to the controller process; static resource files do not.

If the amount of JavaScript is small then leaving it in the page is the simplest approach. If you have more JavaScript, you can create a JavaScript object in the page that has the controller values assigned, and reference that in the JavaScript that is in the static resource.