有时,当我需要在许多网页中包含相同的元素组时,我使用PHP:
< php包含somefile.html?>当 somefile.html 是这样的:
< h1> TITLE< / h1> < h2>小标题< / h2>有时,当我懒得使用PHP并打开本地服务器时,我使用JS:
< script src =somescript.js>< / script>当 somescript.js 是这样的:
document.write(< h1> TITLE< / h1>+ << ; h2>小标题< / h2>);第二个版本稍微不方便一些,但我使用两种方式。
然而,我想知道哪种方式是惯例,哪种方式更快。
我知道PHP是服务器端,并且是预先解析成HTML,但即使它在JS之前加载,我不知道它是否更快。因为JS是客户端,所以它被浏览器解析,并且可能比向服务器发送请求更快(尽管我不完全确定 - 告诉我我是否做出了不正确的推理)。
请随时告诉我,如果我不清楚,并将我重定向到另一个可能有帮助的页面。
谢谢。
解决方案第二种方法不但性能差,而且可能会抹去整个页面,这是一种糟糕的做法,因为 document.write()起作用。你不应该使用 document.write(),除非你非常确定你需要,这很少见。我所知道的唯一可以接受的情况是为cdn提供的javascript的回退。您可以使用它为本地副本编写脚本标记,例如: code.jquery/jquery-latest.js\"></script> < script> window.jQuery || document.write('< script src =sys / lib / jquery.js>< \ / script>')< / script>
请考虑您所包含的脚本位于服务器上,因此请求必须发送它必须在页面可以继续或完成加载之前加载。服务器可能刚刚发送过这些数据。
Sometimes when I need to include the same group of elements in many web pages, I use PHP:
<?php include "somefile.html" ?>When somefile.html is this:
<h1>TITLE</h1> <h2>Subtitle</h2>And sometimes, when I'm too lazy to use PHP and turn on my local server, I use JS:
<script src="somescript.js"></script>When somescript.js is like this:
document.write( "<h1>TITLE</h1>" + "<h2>Subtitle</h2>" );The second version is just a tiny bit more inconvenient, but I use both ways.
However, I was wondering which way is customary and which way is faster.
I know PHP is server-side and is pre-parsed into HTML first, but even though it loads before the JS does, I don't know if it's faster. Because JS is client-side, it is parsed by the browser and might be quicker than sending a request to the server (although I'm not totally sure - tell me if I'm making incorrect inferences).
Feel free to tell me if I'm unclear and redirect me to another page that could help.
Thanks.
解决方案The second way is not only worse performance wise, it's an awful practice that could potentially erase your entire page because of how document.write() works. You shouldn't be using document.write() unless you are VERY sure you need to, which is rare. The only case I know of in which it is acceptable is for fallbacks of cdn delivered javascript. You use it to write in script tags for a local copy, like this:
<script src="code.jquery/jquery-latest.js"></script> <script>window.jQuery || document.write('<script src="sys/lib/jquery.js"><\/script>')</script>Consider that the script you're including is on the server, so a request has to be sent for it and it must be loaded before the page can continue or finish loading. The server could have just sent that data to begin with.
更多推荐
PHP include()还是JS src可以更快地包含文件?
发布评论