简体   繁体   English

JavaScript代码-包括php

[英]javascript code - include php

I have some javascript code in the most of my php files(different javascript code in each file but maybe some functions are also used in more than one files) Is it a good idea to put all the javascript code from all of my pages into one file and just include this file in each page(using the include php function)? 我的大多数php文件中都有一些javascript代码(每个文件中都有不同的javascript代码,但可能多个文件中也使用了某些功能)将所有页面中的所有javascript代码都放在一个文件夹中是个好主意吗文件并仅在每个页面中包含此文件(使用include php函数)? Thank you in advance! 先感谢您!

If the JavaScript code isn't generated dynamically, it'd be better to put it into a separate .js file. 如果不是动态生成JavaScript代码,最好将其放入单独的.js文件中。 That way, the browser can download it once, and then use the same cached copy across multple PHP pages. 这样,浏览器可以下载一次,然后在多个PHP页面上使用相同的缓存副本。

If you copy the JavaScript code into each PHP file, the browser will have to download those duplicate copies. 如果将JavaScript代码复制到每个PHP文件中,则浏览器将必须下载这些重复的副本。 And the output of a PHP page is often not cacheable, which means that the browser would end up re-downloading that JavaScript code each time you reload the same page. 而且,PHP页面的输出通常不可缓存,这意味着浏览器最终将在每次重新加载同一页面时重新下载该JavaScript代码。

Yes, you want to separate your JavaScript from your PHP. 是的,您想将JavaScript与PHP分开。 However, you don't want to use the PHP include() function to make use of your scripts. 但是,您不想使用PHP include()函数来使用脚本。 In the head of your DOM, just use a script tag with a src attribute. 在DOM的开头,只需使用带有src属性的脚本标签。

<head>
  <script type="text/javascript" src='path/to/file.js'></script>
</head>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM