I'm building an application (literally, an online application) and I'd like to dynamically call Js files/functions into play only when they are needed. Additionally, and this is the kicker, it would actually benefit me to be able to pass php variables and functions with return values into the Js code. This way, the variables passed will occur server-side, and I'll have the benefit of only having the client-side code I need at the time.
To this end I'm considering creating multiple PHP files that simple contain the following:
<?
//JS CODE FOR PAGE 1 (ETC.)
//HEADER FUNCTIONS
?>
<script type="text/javascript">
//FUNCTIONS, METHODS, ETC WITH THE ABILITY TO INSERT PHP VARIABLES LIKE SO:
var name = <?= $name ?>
</script>
Does anyone have any objections? Why would this NOT be an efficient way开发者_StackOverflow to manage Js code, call it dynamically by including, and passing data? What am I not thinking of?
In my applications I am also loading only js-files, if needed. I don't know if you do, but I am using a MVC-structure. So while predispatching I am checking if there is an js-file existing with the same name as my controller for example. This way they get only loaded, if the controller/action really needs it. But this way I am only including static js-files, nothing dynamic with PHP-variables. I guess, I just didn't need that so far ;)
But making your js-files related to a controller or action within the controller or both is a very great way to load only the js-files, which I really need.
Maybe you can use the json_encode function of PHP to make your PHP objects usable in JavaScript like <script type="text/javascript">
var name = <?= json_encode($name) ?>;
</script>
精彩评论