What are the advantages to putting your Javascript in a .php file?

前端 未结 7 2498
独厮守ぢ
独厮守ぢ 2021-02-15 12:40

I occasionally come across pages where some Javascript is included via a PHP file:


  
    

        
7条回答
  •  故里飘歌
    2021-02-15 13:18

    If you don't need it, don't use it:

    The first thing you need to keep in mind is YAGNI. You Ain't Gonna Need It. Until a certain feature, principle, or guideline becomes useful and relevant, don't use it.

    Disadvantages:

    • Added complexity
    • Slower than static files.
    • Caching problems (server side)
    • Scalability issues (load balancers offload static files from the heavy PHP/Apache etc processes)

    Advantages:

    • User specific javascript - Can be achieved by initializing with the right variables / parameters in the section of the HTML
    • Page specific javascript - JS could also be generalized to use parameters
    • JSON created from database (usually requested via AJAX)

    Unless the javascript is truely unique (i.e. JSON, parameters/variables) you don't gain much. But in every case you should minimize the amount of JS generated on the server side and maximize the amount of code in the static files. Don't forget that if it's dynamic, it has to be generated/downloaded again and again so it's not wanted for it to be a heavy process.

    Also:

    • This could also be used to minimize the amount of server configuration (for example if the web server doesn't serve file.js with the correct content type)

提交回复
热议问题