简体   繁体   中英

How to run a specific javascript code before page load (first of all)?

I have a js code that adds margin-top to a row with a specific class name (page with id=3) . I would like this code runs before page load because now it instantly displays the row without margin-top and then add it. The row should be displayed with the margin-top already be added.

My site is on wordpress and i added the js script on head.

I have tried window.onpaint = checkMargin(); but it did not work. Any idea?

This is my js code

<script type="text/javascript">   

//sets margin-top in serv-col --- IF not mobile version
 function addServMargin() {
 containers = document.getElementsByClassName('serv-cont');
  titles = document.getElementsByClassName('serv-col-title');
  texts = document.getElementsByClassName('serv-col-text');
  links = document.getElementsByClassName('serv-col-link');

  col_pad = '0px';
  if ( window.innerHeight > 800) { col_pad = '8.3vh'; }

  for (var i = 0; i < titles.length; i++) { 
    title_height = titles[i].offsetHeight;
    text_height = texts[i].offsetHeight;
style = window.getComputedStyle(containers[i], '');
    cont_height = style.getPropertyValue('height');
    cont_padd = style.getPropertyValue('padding-top');
    links[i].style.marginTop = 'calc(' + cont_height + ' - ' + 
cont_padd + ' - ' + col_pad + ' - ' + title_height + 'px - 1.48vh - ' + 
text_height + 'px - 127px - 5vh)';
  }
}
function checkMargin() {
 if (document.getElementsByClassName('page-id-13')[0] && window.innerWidth > 900) { addServMargin(); }
}
window.onresize = checkMargin;

</script>

I don't think making it run first will solve anything. The first thing the code does is get the containers, titles, texts, and links... which it does by searching the DOM. It then loops through the titles array and does the adjusting as needed. If the script runs before any rendering is done, the DOM elements won't exist. It 1) won't be able to find them, and 2) can't loop through them because the array will be empty.

Actually even before that, it checks for the existence of the elements it's looking for, and the screen size. I think the only way to get it to work w/o making it look like an after thought adjustment, would be to use CSS and media sizing to set the styles in the first place.

As I know JS is executed as the script tag is reached by Browser html interpreter. So putting it in the head tag on the first position may guarantee that it strats first, but can't guarantee that it ends execution before page loads, because the page loads asynchroniously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM