Chromium内核浏览器打印WordPress Tufte CSS模板耗时过长问题
问题:Chromium内核浏览器打印Tufte CSS模板文章耗时过长
我在WordPress网站上基于Tufte CSS模板开发了适配打印/PDF的文章模板,但Chrome及Edge等Chromium内核浏览器的打印预览(及后续打印/保存为PDF)耗时极久,Firefox和Safari则无此问题,可通过指定测试链接在不同浏览器中验证表现。
已排查的方向
- 曾怀疑是大文本增加页数或JavaScript函数导致,但测试后Chrome的问题并未改善
- 在Chrome的“模拟CSS打印模式”下加载页面无延迟,仅打印流程中出现耗时问题,目前无法定位Chrome打印渲染阶段的具体耗时原因
页面适配打印使用的JavaScript代码
页面加载时会运行几段JS函数以适配A4打印格式,核心是处理嵌入的交互iframe:
替换/调整iframe以适配打印
检查iFrames是否已替换为打印用静态图片,若是则替换,否则标记并调整尺寸以适配打印边界:
var iframe_exists = false; if ($('iframe').length > 0) { iframe_exists = true; } $("iframe").each(function(index){ if(typeof $("p.print-sub-img")[index] !== 'undefined'){ $(this).replaceWith($("p.print-sub-img")[index]); } else { newDiv = $('<div>').append($(this).clone()); let adjusted_dims = null; adjusted_dims = adjustFrame($(this).width(), $(this).height()); newDiv = $('<div>').append($(this).clone().removeAttr('style').attr({'style': 'width: '+adjusted_dims[0]+'px; height: '+adjusted_dims[1]+'px;'})).attr({'class': 'print-frame', 'align': 'center', 'id': 'iframe-'+index}); $(this).unwrap().replaceWith(newDiv); } });
检查静态图片加载完成状态
确保所有替换后的静态图片加载完成后再触发打印:
// script from seancdavis.com/posts/wait-until-all-images-loaded/ - thanks sean! // Images loaded is zero because we're going to process a new set of images. var imagesLoaded = 0; // Total images is still the total number of <img> elements on the page. var totalImages = $("img").length; // Step through each image in the DOM, clone it, attach an onload event // listener, then set its source to the source of the original image. When // that new image has loaded, fire the imageLoaded() callback. $("img").each(function (idx, img) { console.log('img load check', img) $("<img>").on("load", imageLoaded).attr("src", $(img).attr("src")); }); // Do exactly as we had before -- increment the loaded count and if all are // loaded, call the allImagesLoaded() function. function imageLoaded() { imagesLoaded++; if (imagesLoaded == totalImages) { allImagesLoaded(); } }
生成二维码并触发打印
所有图片加载完成后,生成文章网页版二维码并触发打印命令:
function allImagesLoaded() { console.log('generating qr....') if (iframe_exists == true){ var qrcode = new QRCode($("#qr-code")[0], { text: "<?php echo get_site_url().'/'.$post_slug ?>", width: 128, height: 128, correctLevel : QRCode.CorrectLevel.H }); $('#qr-banner').show(); } window.print(); console.log("print triggered") } });
现寻求帮助定位Chrome及Chromium内核浏览器打印渲染耗时过长的原因。
内容的提问来源于stack exchange,提问作者Mayukh Nair
相关产品推荐
相关产品推荐

