What is the most efficient way to include many javascript functions (with PHP in them) in a PHP page?

In one of my sites, I need to use PHP 'foreach' to keep including some Javascript code. In this code contains PHP $variables that change within the foreach loop.

foreach ($a as $b) {

javascript.php contains codes like this:

   $(".<?php echo $somevariable?>").something;

My question is: What is the most efficient (if any) way to load javascript that contains PHP variables?

I keep reading that it's better to call large javascript codes in a .js script rather than writing it on the page, But apparently .js files can not have PHP.

Thanks for your insight.


Here is the approach I would use:

Create your HTML file with a Javascript variable containing $somevariable:

    <script src="my_global.js"></script>
    var somevariable = "<?php echo $somevariable ?>";

Then have the Javascript file access this value once the page is ready (I'm using jQuery .ready() in this example):

$(document).ready(function() {

Here it is in action: http://jsfiddle.net/2zeQM/

This allows the Javascript file to be cached (it's static and not dynamic). And the dynamic data is loaded on the page being requested by the user.

You do need to be careful that the variable name you use does not get reused by any other Javascript code. To prevent problems, I would prefix the variable name. For example, instead of calling it "somevariable", I might call it "xy_somevariable"

you can add:

header("Content-type: text/javascript");

to the top of your .php file and it will render as a .js file.

Need Your Help

Is Linq "Where" more expensive than Linq "Select"?

c# linq performance select collections

I'm investigating performance on an operation. I'm iterating a subset of items from a collection. I filter this collection using a Linq query. It basically looks like this: