【发布时间】:2018-05-30 04:10:01
【问题描述】:
我的想法是使用 php 或 js 创建大量 div。 (我从昨天开始写js。)
所以我给自己的任务是使用 php 或 js 或两者来生成一个 div 网格。 到目前为止的想法是将一个通用的 div 作为行和内部的小单元格。首先,我使用 php 变量确定行必须有多长,然后我定义行数 [到目前为止很简单]。当我生成我的网格时,我的问题就来了。只使用 php 非常慢,所以我决定也使用 js。我的第一次尝试将时间缩短了一半,但仍然很慢。于是我问自己有没有办法划分js的工作?嗯,是的……当然是使用函数!所以我做了一个叫做扇区的函数并试图调用它。它有效,但仍然太慢。那么做这样的事情的最佳实践是什么?
<?php
$rowWidth = 200; // width in pixels
$rowHeight = 100; // height in pixels
$boxWidth = 1; // box width in pixels
$boxHeight = 1; // box height in pixels
?>
<body>
<script>
function sector(sector) {
for (var i = 0*sector; i < (<?php echo $rowHeight / 100 ?> + 100*sector); i++) { // trying to manage sectors
var div = document.createElement('div');
// set style
div.style.width = '<?php echo $rowWidth ?>';
div.style.height = '<?php echo $boxHeight ?>';
div.style.background = 'red';
div.setAttribute('class', 'row'); // and make a class for future css (for now using inline css set by js)
div.setAttribute('id', 'row'+i); // and make an id selector
document.body.appendChild(div);
for (var e = 0; e < <?php echo $rowWidth ?>; e++) {
var box = document.createElement('div');
// set style
box.style.width = '<?php echo $boxWidth ?>';
box.style.height = '<?php echo $boxHeight ?>';
box.style.float = 'left';
box.style.background = 'pink';
box.setAttribute('class', 'box'); // and make a class for future css (for now using inline css set by js)
box.setAttribute('id', 'box'+e); // and make an id selector
document.getElementById('row'+i).appendChild(box); // joining my row
}
}
}
<?php for ($sector=0; $sector < ($rowWidth / 100) ; $sector++) { ?>
//calling all sectors, calling all sectors... please report
sector(<?php echo $sector+1 ?>);
<?php } ?>
</script>
</body>
更新: 这看起来和我的想法很相似。
他们是怎么做到的?
【问题讨论】:
-
您是否尝试在其上设置一个计时器以查看其减速的位置?就我而言,它是展示整个该死的东西。所以我把它放到 bootgrid 中让它更快
-
a) 为什么您要显示一百万个 div b) PHP 与此有什么关系 c) 是什么让您认为有一种方法可以显示一百万个 div没有性能影响?
-
你不能简单地将一百万个div输出到用户的浏览器,它会很慢......如果可能的话,可能会将它们分成页面,否则我认为不可能。跨度>
-
最好的做法是不这样做。第 1 步不使用一百万个 div,因为那会杀死浏览器。研究使用 HTML5 画布元素。第 2 步不是将单个像素存储在数据库中,因为这会杀死您的数据库。查看实际的图像格式。第 3 步就是使用 PNG 或 JPG 或 GIF ...
-
正如其他人所说,没有办法优化显示 100 万个 div,因为浏览器不是为渲染 100 万个 div 而设计的。除非您专门为此目的创建自己的浏览器+渲染引擎,否则无论如何这都会很慢。仅您的网页的绝对大小将是可笑的,对于页面 DOM 而言 > 10mb。在您发布的示例中,他们使用了一个画布元素,并绘制到画布上。
标签: javascript php jquery html performance