Page 1 of 1

Writing an external javascript in PHP

Posted: Sat Dec 06, 2008 1:26 am
by saltriver
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:

Code: Select all

<script type="text/javascript" src="js/myjavascript_js.php"></script>
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

 
<?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 '}';
 
 
?>
 

Re: Writing an external javascript in PHP

Posted: Sat Dec 06, 2008 5:41 am
by JAB Creations
What you did that I do not agree with is to use double quotes in JavaScript. I only use double quotes for XHTML, single quotes for JavaScript, and no quotes for CSS.

Any way this renders the JavaScript though I'm not entirely certain the JavaScript itself will work...that's up to you. :wink:

Now what I would recommend in situations where you only need to have PHP echo out one or two things is to only output the JavaScript from PHP at those points...and not the entire JavaScript file itself!

Any way hope this helps!

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 "}"; 
?>

Re: Writing an external javascript in PHP

Posted: Sat Dec 06, 2008 8:53 am
by Syntac
Eh, JAB? If I remember correctly, you need quotes in CSS for it to validate properly.

Re: Writing an external javascript in PHP

Posted: Sat Dec 06, 2008 9:22 am
by JAB Creations
Nop, validates fine for me. :P There was an older browser that couldn't handle quotes in CSS...can't remember off the top of my head.

Re: Writing an external javascript in PHP

Posted: Sun Dec 07, 2008 6:17 pm
by kaszu
Double quotes in php shouldn't be used if not needed.

Code: Select all

<?php
 
     // Author: Brian J Clifton
     // Url: http://www.advanced-web-metrics.com
 
 ?>
window.onload = addLinkerEvents;
function addLinkerEvents() {
var as = document.getElementsByTagName('a');
var extTrack = ['<?php echo addslashes($_SERVER["SERVER_NAME"]); ?>'];
 
var extDoc = ['.doc','.xls','.exe','.zip','.pdf','.js'];
 
for(var i=0; i<as.length; i++) {
    var flag = 0;
    var tmp = as[i].getAttribute('onclick');
 
    if (tmp != null) {
        tmp = String(tmp);
        if (tmp.indexOf('urchinTracker') > -1 || tmp.indexOf('_trackPageview') > -1) continue;
    }
 
    for (var j=0; j < extTrack.length; j++) {
        if (as[i].href.indexOf(extTrack[j]) == -1 && as[i].href.indexOf('google-analytics.com') == -1 ) {
            flag++;
        }
    }
       
    if (flag == extTrack.length){
        var splitResult = as[i].href.split('//');
        as[i].setAttribute('onclick', 'pageTracker._trackPageview('/ext/' +splitResult[1]+ '');'+((tmp != null) ? tmp+';' : ''));
    }
 
    for (var j=0; j< extDoc.length; j++) {
        if (as[i].href.indexOf(extTrack[0]) != -1 && as[i].href.indexOf(extDoc[j]) != -1) {
            var splitResult = as[i].href.split(extTrack[0]);
            as[i].setAttribute('onclick',((tmp != null) ? tmp+';' : '') + 'pageTracker._trackPageview('/downloads' +splitResult[1]+ '');');
            alert(splitResult[1])
            break;
        }
    }
 
    if (as[i].href.indexOf('mailto:') != -1  && as[i].href.indexOf('gashbug@google.com') == -1 ) {
        var splitResult = as[i].href.split(':');
        as[i].setAttribute('onclick',((tmp != null) ? tmp+';' : '') + 'pageTracker._trackPageview('/mailto/' +splitResult[1]+ '');');
            //alert(splitResult[1])
        }
    }
       
}
Also headers sent by server must have correct content type, otherwise it may not work. If files extension is not "js" but "php" or something, then add following to the beginning of the file

Code: Select all

<?php header("Content-type: application/x-javascript"); ?>