问题
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.
回答1:
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.
回答2:
The first is definitely more customary, more efficient, and faster.
These are the actions I can point out to simply count the network and i/o interactions from a very high level.
php include:
- User requests
- apache processes
- php processes from disc
- apache sends data for display
js include:
- user requests
- apache processes
- (assuming html extension is not processed by php)
- apache sends data for display
- js tells browser to include another file
- apache processes request for another file
- apache sends data for inclusion
- js process displays data
回答3:
The first method is slower for the server, and the second is slower for the client. Though, in practice, both methods should be fast enough for normal use cases. I would recommend the first method though.
来源:https://stackoverflow.com/questions/20436082/is-php-include-or-js-src-to-include-file-faster