Printing from Chrome is becoming a time-consuming process for this particular webpage

I've been working on creating a print/PDF-friendly template for articles on a WordPress site by customizing the Tufte CSS template.

However, I'm facing an issue where the print preview render (and subsequent printing/saving as PDF) is extremely slow on Chrome and browsers with Chromium cores like Edge. Interestingly, this problem doesn't occur on Firefox and Safari. You can test it yourself on this link using Chrome/Edge/(Chromium based browser), Safari, and Firefox.

I suspected that perhaps the large text was causing an increase in the number of pages or maybe the JavaScript functions were to blame. However, testing these theories hasn't made any difference to how Chrome behaves. Interestingly, when loading the page in Chrome's "Emulate CSS print mode," there doesn't seem to be any delay until the actual printing process.

The mystery lies in not knowing what exactly Chrome is doing during the rendering process, which has been frustrating me.

There are a couple of JavaScript functions that execute upon page load to make the content more print-friendly for the A4 format. These functions mainly deal with handling interactive iFrames embedded within the post to ensure they are print-ready.

To address this, check if any iFrames have been replaced with static images for printing purposes. If so, substitute them back with their original iFrames. Otherwise, tag and resize each iFrame to fit within the printable area:

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);
            }
        });

Ensure that the substitution of static images for iFrames has been successfully completed:

// script from https://www.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"));
        });

        // Increment the loaded count for each loaded image, and trigger allImagesLoaded() when all are done loading.
        function imageLoaded() {
            imagesLoaded++;
            if (imagesLoaded == totalImages) {
            allImagesLoaded();
            }
        }

Generate a QR code linking to the web version of the article, and initiate the print command:

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")
    }
    });

Answer №1

The issue causing the hang is not related to JavaScript or Iframes, but rather to a CSS file! The problem lies within the @media print section of that file:

@media print {
...
a:link[href] {
    text-decoration: underline;
    /* color: darkblue; */
}
...
}

The main issue here is the selector for the a:link[href] tag. It logically should be in a different order. However, simply rearranging it will not resolve the problem. You need to decide whether to use an attribute or pseudo for the selector rule. In this case, :link will suffice for all requirements (:link will not work for a without href, you can try it here).

a:link {
    text-decoration: underline;
}

This seems to be a bug in the Chrome print preview engine, as the selector is valid when properly ordered.

There are also some incorrect block comments present, but they do not affect the functionality of the preview.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Set the background color of the container row to extend the full width, encompassing

I am working on a grid container and I want to change the background color of the second row within it. Check out my Fiddle This is the HTML markup: <div class="totalContainer totalContainer__space"> <div class="totalContainer__ ...

Ways to retrieve all elements following a chosen element

Is there a way to include the last element too? $('div.current').nextUntil("div:last").css("color", "blue"); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div>First</div> < ...

Table borders disappear when loading PHP echoed tables with jQuery and Ajax

Currently, I am delving into the world of jQuery, PHP, AJAX, and MySQL. My objective is to retrieve a table from the MySQL server and exhibit it on a webpage. This involves two PHP files – one serves as the back-end script connecting to the database and ...

Is there a maximum number of window.open() calls that can be made in JavaScript?

Can the use of window.open("URL"); in JavaScript be limited? Upon attempting to open three windows using window.open("URL"), the third window did not open separately. Instead, it refreshed the contents of the first window and displayed the contents of ...

Unleashing the Power of Object Destructuring in React Hooks

Here is a straightforward code snippet: import React from "react"; import { useForm } from "react-hook-form"; export default function App() { const { register, formState: { errors }, handleSubmit } = useForm(); return ( < ...

a new approach for creating a conditional function in pointfree fashion

Can someone help me convert this code into a pointfree style? To provide context: The function receives an Array of Either types and returns a Task type. If any of the Either types have the left set, the Task type is rejected with that value. If none of t ...

Concealing specific DIV elements (unfortunately not nested)

Currently, I am dealing with pre-existing code that is automatically generated and needs to adhere to a specific format: <div id="TITLE1"></div> <div id="div-1"></div> <div id="div-2"></div> <div id="div-3"></d ...

What exactly is Bootstrap - a CSS framework, a JavaScript framework, or a combination

Being new to Bootstrap, I have taken the time to explore What is Bootstrap? as well as http://getbootstrap.com/. From what I understand so far, Bootstrap is a CSS framework that aids in creating responsive designs that can adapt to various devices. Essent ...

The JavaScript function on the specified /url page is not functioning properly following the execution of history.push(/url) on click

I have a JavaScript function that toggles the display of login password. However, when I redirect to the login page from another page using history.push(/login), the function does not work. It does work when I use (/login) in the href tag. How can I resolv ...

dc.js selects a chart that has already been rendered

I am attempting to manually adjust the width of a pie chart that has already been generated. The chart is constructed and displayed using an angular factory and directive, and I want to access this chart from a controller. Is there a method similar to var ...

Issue with applying Bootstrap button style to buttons

I have been attempting to customize these buttons using my CSS, but unfortunately, they are not reflecting the desired style. Even after creating new buttons, I encountered the same issue where they did not adhere to the CSS. Upon closer inspection, I not ...

Is there a way to customize the background color of a dropdown menu?

Is there a way to change the background color of my dropdown menu when it is open? I have tried using the following CSS code: .dropdown.open { background-color: black; } Here is how the HTML looks like: <ul class="nav navbar-nav navbar-right"> ...

Can you explain the meaning of `bind(this)`?

Understanding how bind works is essential for binding objects or functions to desired functions. However, the usage of bind(this) can be perplexing. What exactly does this refer to in the context of the bind function? Here is an example of code snippet fr ...

Ensuring elements are correctly positioned

I am struggling to make the images in the following code align horizontally across the top and also need to align the h1's in the same way. I have tried using the vertical-align property, but it seems to behave oddly to me. HTML: <div class=&apos ...

Utilize JavaScript Datepicker within the RStudio Environment

Can anyone help me figure out how to add a javascript datepicker to my Shiny app? I'm not sure how to import and execute the code in R. Here is where I found the source code: http://jqueryui.com/datepicker/ I'd prefer to integrate this code into ...

CSS Styles Only Apply to the Initial Column on the Website

It seems like the css is only working on the first column to display the item-meta. Everything appears to be in place when inspected, but for some reason, the opacity does not change back to 1. It's strange because it works fine in the first column ev ...

Encountered an issue while attempting to send a POST request using AngularJS $

I am facing an issue with accessing the POST method from my server. Whenever I log the response, it always returns status=0. Can anyone help me out or provide some advice? Note: I have tested the method in Postman and it works fine. Below is the code snip ...

The custom width is not being applied to the Bootstrap column

I'm working on a Web Design project using Bootstrap. Here is a snippet of my HTML code: <div class="col utility_col"> <div class="row"> <div class="col vote_col">Vote</div> <div class="col sign_col"> < ...

Using JQuery to attach a click event to a div element

My HTML code looks something like this: <div class="vmail vmail-bar normal-vmail-bar" id="pm_<?php echo $pm->to_id; ?>"> <div class="checkbox"><input type="checkbox" class="checkbox" /></div> ...

Struggling to retrieve the value in Node.js

Currently, I am in the process of developing a Node.js script to perform the following tasks: Read a file line by line Identify a regex match and store it in a variable Utilize this value in subsequent operations Below is the code snippet that I have im ...