PHP include()还是JS src可以更快地包含文件? [英] Is PHP include() or JS src to include file faster?

查看:148
本文介绍了PHP include()还是JS src可以更快地包含文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,当我需要在许多网页中包含相同的元素组时,我使用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>
);

第二个版本稍微不方便一些,但我使用两种方式。



然而,我想知道哪种方式是惯例,哪种方式更快。<​​/ b>

我知道PHP是服务器端,并且是预先解析成HTML,但即使它在JS之前加载,我不知道它是否更快。因为JS是客户端,所以它被浏览器解析,并且可能比向服务器发送请求更快(尽管我不完全确定 - 告诉我我是否做出了不正确的推理)。



请随时告诉我,如果我不清楚,并将我重定向到另一个可能有帮助的页面。



谢谢。

解决方案

第二种方法不但性能差,而且可能会抹去整个页面,这是一种糟糕的做法,因为 document.write()起作用。你不应该使用 document.write(),除非你非常确定你需要,这很少见。我所知道的唯一可以接受的情况是为cdn提供的javascript的回退。您可以使用它为本地副本编写脚本标记,例如: code.jquery.com/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="http://code.jquery.com/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可以更快地包含文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆