问题
Approach 1:
Using CSS display:none
means that the content is sent to the client but is hidden from view. In other words; the content does exist but without occupying any space.
Approach 2:
Using if(false){content}
prevents the content from being sent to the client at all.
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Approaches</title>
</head>
<body>
<div <?php if (true) {echo 'style="display:none;"';}?>>
Approach 1
</div>
<?php if (false): ?>
<div>
Approach 2
</div>
<?php endif; ?>
</body>
</html>
Which is regarded better in terms of security practices?
If both are secure, then which is regarded better in terms of performance and code design methodology?
回答1:
Definitely Approach 2
If you don't want the client to view your content, then not sending it to them at all is always better.
Approach 1 verdict:
- If you send them the div's content, then they can always view your page's source and see it there, even though it's not shown to them on screen.
Approach 2 verdict:
- Because the content is never sent to them in the first place, they can't see it even if they view source.
回答2:
For security practices, definitely for approach #2. Let's say your "hidden" div contains sensitive information that it's only ment for Admin level. If you simple put the CSS on display none, they can view the HTML content and see the sensitive information.
For performance practices, as far as I remember, your browser does render the hidden div, but doesn't show it. So the HTML is downloaded and parsed, but not shown.
I would go for the approach #1, if you want to show hidden div's when someone clicks on a certain button on that specific page. For example, if you have a "Read more..." button that should show the rest of the content (which in a separate div).
来源:https://stackoverflow.com/questions/44196694/apply-css-displaynone-or-use-iffalsecontent-to-block-content-at-clients