Well … HTML-wise the scripts should be put into the header, or better, at the footer – which this function should handle – and not somewhere "random" in the script …