Writing an external javascript in PHP

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
saltriver
Forum Commoner
Posts: 59
Joined: Fri Mar 12, 2004 2:40 pm
Location: Burlington, VT

Writing an external javascript in PHP

Post 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 '}';
 
 
?>
 
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Re: Writing an external javascript in PHP

Post 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 "}"; 
?>
User avatar
Syntac
Forum Contributor
Posts: 327
Joined: Sun Sep 14, 2008 7:59 pm

Re: Writing an external javascript in PHP

Post by Syntac »

Eh, JAB? If I remember correctly, you need quotes in CSS for it to validate properly.
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Re: Writing an external javascript in PHP

Post 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.
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Writing an external javascript in PHP

Post 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"); ?>
Post Reply