javascript - 注释不在浏览器源代码中显示
天蓬老师
天蓬老师 2017-04-11 11:03:13
[JavaScript讨论组]

怎么使注释不在浏览器源代码中显示

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(6)
ringa_lee

可以在服务器端实现, mod_pagespeed是一个Apache module,去空白去注释,还有那些合并css等等很多功能
http://www.modpagespeed.com/

原始状态:

<html>
<body>
<!-- Display the site logo here -->
<img src="logo.png">
<!-- Now show the page contents -->
<p>Some content here</p>
<!-- Apply IE-specific CSS -->
<!-- [if IE ]>
<link href="iecss.css" rel="stylesheet" type="text/css">
<![endif]-->
<!-- google_ad_section_end  -- retained due to RetainComment directive -->
</body>
</html>

输出之后:

<html>
<body>
<img src="logo.png">
<p>Some content here</p>
<!-- [if IE ]>
<link href="iecss.css" rel="stylesheet" type="text/css">
<![endif]-->
<!-- google_ad_section_end  -- retained due to RetainComment directive -->
</body>
</html>
PHP中文网

删除了不就不显示了,哈哈

天蓬老师

同楼上,浏览器的“查看源代码”会默认吧所有代码显示出来,只有删除这个方案 —— 问题是怎么删比较好?

如果觉得手动删比较麻烦,可以在上线前把代码统一用HTML压缩工具压缩一遍,同时就去掉注释了。

注意,这么做的话html代码本身的缩进、不必要的空格也会被删,所以请复制一份html来压缩。

另外,有精力的话也可以自己用脚本语言写一个批量删除html注释的小工具。

PHP中文网

可以联系浏览器厂商,让他们加一个隐藏源代码注释的功能

黄舟

只能服务器端不输出,没有什么办法

PHP中文网

注释也属于节点, 你可以遍历节点找出所有node_type == document.COMMENT_NODE 然后remove().


// 临时写的, 遍历然后移除注释 
;(function(){
  var result = [], comment, nodelists;
  walker= document.createTreeWalker(document, NodeFilter.SHOW_COMMENT, null, null);
  while(comment = walker.nextNode()) {result.push(comment)}; //遍历迭代器
  result.map(function(item) {item.remove()})
}());
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号