Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

How to alter the original HTML while it's still loading

I need to use some data, calculated by JS (for example: window size) as css property of some HTML element. To avoid flickering of the window because of layout changes, I can't afford to use document.onready. I actually need to trigger JS function at the time the DOM element is added to the DOM tree.

I've tried with DOMNodeInserted event, but it seems that it triggered only for elements that are added post-loading the HTML code, with JavaScript.

What I need is to change tag that is presented in the original HTML source of the page. So for now I just inline JavaScript just after the HTML code of the tag that has to be changed, but is there a way to do this without inlining JS after every such tag. Something like DOMNodeInserted, but triggered while the original HTML is being rendered. Or how else I can accomplish this - having a JS dependent layout that does not move after it's loaded (it's properly generated before showing it to the user) and still have HTML code in the page (e.g. do not generate the page entirely from JavaScript)?

UPDATE here is the javascript that is used to resize image. It respects both width and height, while widht:100% or height:100% works unless the window width/height is not smaller then image itself.

function resizeImg() {
    var imgwidth = bgImg.width();
    var imgheight = bgImg.height();

    var winwidth = $(window).width();
    var winheight = $(window).height();

    var imgratio = imgwidth / imgheight;

    imgwidth = winwidth;
    imgheight = winwidth / imgratio;


    if (imgheight < winheight) { 
        imgheight = winheight;
        imgwidth = imgheight * imgratio;
    }

    $('.cover-image').css({
        width: winwidth+'px',
        height: winheight+'px'
    });
}

Upvotes: 1

Views: 188

Answers (1)

kennebec
kennebec

Reputation: 104770

You can use a script to compose a stylesheet and add it to a new style element on the head before the body renders.

Or you can use media queries in a style sheet and apply the styles you prefer for different window or device dimensions.

Upvotes: 2

Related Questions