Use PHP code in external Javascript file

前端 未结 5 394
甜味超标
甜味超标 2020-12-01 05:54

I am just wondering if it\'s possible to use external JS file that contains PHP code.

my external JS

$(document).ready(function(){

    $(\'#update\         


        
5条回答
  •  有刺的猬
    2020-12-01 06:31

    Just a quick idea, that could help some people:

    I think (never tried) there is also a way to ask the web server (Apache, etc) to let JS files be handled as PHP content.

    Advantages:

    • No need to rename your JS files to .js.php
    • Takes advantage of caching
    • Can be applied only to a specific folder (not to every JS file of your website)

    Withdraws:

    • Do not forget that those "php" files are "cached" somewhere, so don't rely on the fact that files are generated every time.
    • Server resources: as said in other answers, make sure to use such a trick only when it's really not possible to put PHP code outside of the JS files (using ajax queries for instance), or on files that don't load the server too much.

提交回复
热议问题