Search code examples
cssfunctionreload

reload css at the end of a function


I'm trying to reload only the CSS of my page at the end of my "print" function, but I can not find anything that works.

I tried with location.reload (); but that reloads the page entirely.

Do you have an idea ?

function print() {
const filename  = 'File.pdf';

    html2canvas(document.querySelector('#print')).then(canvas => {
        let pdf = new jsPDF('p', 'mm', 'a4');
        pdf.addImage(canvas.toDataURL('image/jpeg'), 'JPEG', 0, 0, 211, 298);

        pdf.save(filename);
    });

location.reload ();

}

Solution

  • +Here are two options to reload your css file. In your print() function remove location.reload(). See the added code below.

    function print() {
        const filename  = 'File.pdf';
    
        html2canvas(document.querySelector('#print')).then(canvas => {
            let pdf = new jsPDF('p', 'mm', 'a4');
            pdf.addImage(canvas.toDataURL('image/jpeg'), 'JPEG', 0, 0, 211, 298);
            pdf.save(filename);
        });
    
        // insert your css filename in place of style.css
        document.querySelector('head').innerHTML += 
            '<link rel="stylesheet" href="style.css?' + 
            new Date().getTime() + // add the date string to avoid caching
            '">';
    }
    

    Another way to do it is to dynamically create a style link.

    // insert your css filename in place of style.css
    var css = document.createElement("link");
        css.setAttribute("rel", "stylesheet");
        css.setAttribute("type", "text/css");
        css.setAttribute("href", "style.css?" + new Date().getTime());
    document.getElementsByTagName("head")[0].appendChild(css);
    

    Hope this helps.