It is easy. Save your javascript code in a new one file and then use this to load it:
include('myjavascript.php');
Then you will use the include option as a echo because the web will understand your code as HTML and you execute it when you want with php (like echo).