使用document.write在PHP中编写JS

This is failing but i dont know how to make it work.

I have a php array:

$swipe_list = array('customers.html', 'index.html', 'atr_backplane.html');

This is to know which pages have carousels and need touch support.

so i check the page in php and if its listed the JS will check its a touch device and write the addional js mobile file.

is it because the server script trys ti run before the js can detect at the client side??

<?php
if(in_array($selected, $swipe_list)){ ?>
<script type="text/javascript">

function isTouchDevice(){ document.write('<script type="text/javascript" src="js/jquery.mobile.custom.min.js"></script>')
}

</script>            
<?php }?>
<?php if(!in_array($selected, $exclude_list)){       
print '<script type="text/javascript" src="js/camera.js"></script>';
}
?>

When you use document.write after the page has loaded, all kinds of bad things can happen. I don't remember the exact reason why, but I know it breaks the DOM somehow.

The best thing would be to include the script dynamically without breaking the DOM using something like this instead:

function isTouchDevice(){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'js/jquery.mobile.custom.min.js';
    document.getElementsByTagName('head')[0].appendChild(script);
}

This creates the script element and appends it to the head of the document.

your problem resides here, i think :

function isTouchDevice(){ document.write('<script type="text/javascript" src="js/jquery.mobile.custom.min.js"></script>')
}

There are a number of reasons why this line does nothing.

First, the function isTouchDevice is defined, and then never called (at least not in your example)

Second, writing text to the document after it has loaded isn't a viable way to load external scripts.

From what i gather, you want to do this: (it is also fine to use php's print or echo functions to print the script tag to the document if you don't like this route)

<?php
if(in_array($selected, $swipe_list))
{ 
?>

   <script type="text/javascript" src="js/jquery.mobile.custom.min.js"></script>

<?php 
}

if(!in_array($selected, $exclude_list))
{

?> 

   <script type="text/javascript" src="js/camera.js"></script>

<?php
}
?>

Not sure if your problem is with the inclusion of the js files, but I think if you just remove document.write and include your scripts then it should work:

    <?php
if(in_array($selected, $swipe_list)){ ?>

  <script type="text/javascript" src="js/jquery.mobile.custom.min.js"></script>
<?php
} 

if(!in_array($selected, $exclude_list)){       
?>
   <script type="text/javascript" src="js/camera.js"></script>
<?php
}
?>

try it out :)