[英]How to run a specific javascript code before page load (first of all)?
我有一個js代碼,將margin-top添加到具有特定類名的行(id = 3的頁面)。 我希望這段代碼在頁面加載之前運行,因為現在它立即顯示不帶margin-top的行,然后添加它。 應顯示該行,並已添加邊距頂部。
我的網站在wordpress上,我在頭上添加了js腳本。
我已經嘗試過window.onpaint = checkMargin(); 但它沒有用。 任何想法?
這是我的js代碼
<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>
我認為讓它先運行不會解決任何問題。 代碼要做的第一件事是獲取容器,標題,文本和鏈接……這是通過搜索DOM來完成的。 然后,它遍歷titles數組並根據需要進行調整。 如果腳本在完成渲染之前運行,則DOM元素將不存在。 1)無法找到它們,2)無法遍歷它們,因為數組將為空。
實際上,即使在此之前,它也會檢查要查找的元素是否存在以及屏幕大小。 我認為,使其不像經過深思熟慮的調整那樣工作的唯一方法是,首先使用CSS和媒體大小調整來設置樣式。
據我所知,JS是通過瀏覽器html解釋器到達腳本標簽而執行的。 因此,將其放在head標簽的第一個位置上可以保證它首先分層,但是不能保證它在頁面加載之前結束執行,因為頁面是異步加載的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.