Writing an external javascript in PHP
Posted: Sat Dec 06, 2008 1:26 am
So I have fairly lengthy javascript that needs to go into the head of the page, and for SEO reasons I'd like to have it be an external file. The JS needs to have some variables plugged into it which is why I need (I think) to write in PHP. My instinct is to echo all of the JS without the beginning and ending tags and call it as I would any other JS file like so:
When I view the file in my browser it displays the code (though without line breaks) like any other JS file would. Does this method have any chance of working?
I've tried with just a basic alert, switching between a real JS file and my PHP-JS file. The real one works as expected, but not the PHP.
Here is the JS I'm trying to use:
Code: Select all
<script type="text/javascript" src="js/myjavascript_js.php"></script>I've tried with just a basic alert, switching between a real JS file and my PHP-JS file. The real one works as expected, but not the PHP.
Here is the JS I'm trying to use:
Code: Select all
<?php
// Author: Brian J Clifton
// Url: http://www.advanced-web-metrics.com
echo 'window.onload = addLinkerEvents;';
echo 'function addLinkerEvents() {';
echo 'var as = document.getElementsByTagName("a");';
echo 'var extTrack = ["'.$_SERVER["SERVER_NAME"].'"];';
echo 'var extDoc = [".doc",".xls",".exe",".zip",".pdf",".js"];';
echo 'for(var i=0; i<as.length; i++) {';
echo 'var flag = 0;';
echo 'var tmp = as[i].getAttribute("onclick");';
echo 'if (tmp != null) {';
echo 'tmp = String(tmp);';
echo 'if (tmp.indexOf(\'urchinTracker\') > -1 || tmp.indexOf(\'_trackPageview\') > -1) continue;';
echo '}';
echo 'for (var j=0; j < extTrack.length; j++) {';
echo 'if (as[i].href.indexOf(extTrack[j]) == -1 && as[i].href.indexOf(\'google-analytics.com\') == -1 ) {';
echo 'flag++;';
echo '}';
echo '}';
echo 'if (flag == extTrack.length){';
echo 'var splitResult = as[i].href.split("//");';
echo 'as[i].setAttribute("onclick", "pageTracker._trackPageview(\'/ext/" +splitResult[1]+ "\');"+((tmp != null) ? tmp+";" : ""));';
echo '}';
echo 'for (var j=0; j< extDoc.length; j++) {';
echo 'if (as[i].href.indexOf(extTrack[0]) != -1 && as[i].href.indexOf(extDoc[j]) != -1) {';
echo 'var splitResult = as[i].href.split(extTrack[0]);';
echo 'as[i].setAttribute("onclick",((tmp != null) ? tmp+";" : "") + "pageTracker._trackPageview(\'/downloads" +splitResult[1]+ "\');");';
echo 'alert(splitResult[1])';
echo 'break;';
echo '}';
echo '}';
echo 'if (as[i].href.indexOf("mailto:") != -1 && as[i].href.indexOf("gashbug@google.com") == -1 ) {';
echo 'var splitResult = as[i].href.split(":");';
echo 'as[i].setAttribute("onclick",((tmp != null) ? tmp+";" : "") + "pageTracker._trackPageview(\'/mailto/" +splitResult[1]+ "\');");';
//alert(splitResult[1])
echo '}';
echo '}';
echo '}';
?>