简体   繁体   English

Javascript 代码在初始页面加载时未执行

[英]Javascript code not getting executed on initial page load

I have written a Javascript function for resizing the Carousel according to the screen width.我写了一个 Javascript function 用于根据屏幕宽度调整轮播的大小。 It's doing the job properly but the only issue is that it doesn't get initialized on the initial page load.它工作正常,但唯一的问题是它没有在初始页面加载时被初始化。 The Carousel is only present on the homepage and when I visit it for the first time, the code doesn't get executed. Carousel 只出现在主页上,当我第一次访问它时,代码不会被执行。 However, if I reload the page it does get executed.但是,如果我重新加载页面,它会被执行。 It even gets executed when I resize my browser window.当我调整浏览器 window 的大小时,它甚至会被执行。 But I would like it to initialize on the first first load as well.但我也希望它在第一次加载时初始化。 Here's the code:这是代码:

let carousel = document.querySelector('#carousel');
if (carousel) {
  const size = 0.8;
  window.addEventListener('resize', () => {
    let width = carousel.clientWidth || carousel.offsetWidth;
    let carouselHeight = (width * size) + 'px';
    carousel.querySelector(".slide").style.height = carouselHeight;
  }, false);
} 

You're adding a listener, but the callback won't get called unless it is triggered.您正在添加一个侦听器,但除非触发回调,否则不会调用回调。

You can instead declare the callback as a function, add the listener with the function as callback, and then call the function directly for the initial load.您可以改为将回调声明为 function,添加带有 function 的侦听器作为回调,然后直接调用 function 进行初始加载。

function resizeCarousel(size) {
    let width = carousel.clientWidth || carousel.offsetWidth;
    let carouselHeight = (width * size) + 'px';
    carousel.querySelector(".slide").style.height = carouselHeight;
}

let carousel = document.querySelector('#carousel');
if (carousel) {
  const size = 0.8;
  window.addEventListener('resize', () => resizeCarousel(size), false);
   
  resizeCarousel(size);
} 

You're adding an event listener on the page resize.您正在调整页面大小时添加事件侦听器。 First of all, this should all be wrapped in an on load event listener so you can be sure that the element #carousel is even available.首先,这都应该包含在加载事件侦听器中,这样您就可以确保元素 #carousel 甚至可用。 Then, I would execute the resize function manually by maybe defining the function in the on load event function.然后,我将通过在加载事件 function 中定义 function 来手动执行调整大小 function。 Then set it for resizing events.然后将其设置为调整事件大小。 I'm on my phone so it's hard to type an example, for for example:我在手机上,所以很难输入示例,例如:

document.addEventListener("DOMContentLoaded", function(event) { 
    function resize() { /* Resize Function. */ }
    var carousel = document.querySelector('#carousel');
    window.addEventListener(“resize”, resize);
    resize(); // Call it now as well as onresize.
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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