简体   繁体   English

通过Javascript动态添加元素而不是使用CSS隐藏

[英]Dynamically adding elements via Javascript versus hidden with CSS

I am wondering about the pros/cons of adding elements to a page and setting display:none versus creating a function that will dynamically create the elements and append them where they need to go. 我想知道向页面添加元素和设置display:none与创建一个动态创建元素并将它们附加到需要的位置的函数的优缺点。

In my case I am doing a reply box that gets attached to whatever comment you want to reply to. 在我的情况下,我正在做一个回复框,它附加到您要回复的任何评论。 Atm I just have it hidden via CSS and then move it to whatever node I want with an onclick function. 我只是通过CSS隐藏它,然后通过onclick函数将其移动到我想要的任何节点。 Is there a better way? 有没有更好的办法? I am quite new to taking into account DOM rendering times etc, but I wanna get it right from now on. 考虑到DOM渲染时间等,我还很陌生,但我想从现在开始就把它弄好。

I would prefer using JavaScript to dynamically generate element on client side.. 我更喜欢使用JavaScript在客户端动态生成元素。

Reasons 原因

  • You HTML will be less.. 你的HTML会更少..
  • You can append that anywhere.. 你可以在任何地方追加..
  • You don't need to use unnecessary CSS to hide/show your elements.. 您不需要使用不必要的CSS来隐藏/显示您的元素..

Even the plus side will be that if the user's browser JavaScript is turned off than it wont be a big thing as anyways as you hide the elements using CSS on load, than by using JavaScript these elements won't load at all 即使是好的方面,如果用户的浏览器JavaScript被关闭,那么无论如何你都不会使用CSS在加载时隐藏元素,而不是使用JavaScript这些元素根本不会加载

Perhaps the biggest difference between the two is that content that is included in your HTML can be crawled by search engines. 也许两者之间最大的区别是,HTML中包含的内容可以被搜索引擎抓取。 DOM elements that are added via Javascript will not be. 通过Javascript添加的DOM元素不会。

As far as DOM rendering times, there should not be much of a difference, as long as your code is clean and well-written. 就DOM渲染时间而言,只要您的代码干净且编写良好,就不会有太大差异。

Showing & Hiding with CSS will, I'm sure, always be faster than JS. 我确信,显示和隐藏CSS将始终比JS更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM