简体   繁体   中英

ng2 + webpack refer html dom element in external library

Hello Angular 2 and Webpack developers, I have been working with angular 2 and systemjs since quite a while, new to webpack (starting to love it with a bit of struggle).

I have a component that has html as follows:

  <div id="partners-slider" class="partners">
        <div class="partners__slider js-slick-slider">
          <a class="partners__item"><img src="assets/logo-company-1.png" alt="">Elite Construction Group, LLC</a>
          <a class="partners__item"><img src="assets/logo-company-2.png" alt="">Pro Era Limited</a>
         </div></div>

Its basically a slider. I have a library that I use in a lot of projects, for animations and stuffs.

Theres a function as follows that initiates a slider:

function initPartnersSlider(container) {
var $partnersSlider = $(container) ;
if (!$partnersSlider.length) return;

$partnersSlider
  .find('.js-slick-slider')
  .slick({
    dots: false,
    infinite: true,
    speed: 300,
    slidesToShow: 5,
    autoplay: true,
    accessibility: false,
    prevArrow: $partnersSlider.find('.js-partners-prev'),
    nextArrow: $partnersSlider.find('.js-partners-next'),
    responsive: [
      {
        breakpoint: 1100,
        settings: {
          slidesToShow: 4
        }
      },
      {
        breakpoint: 1000,
        settings: {
          slidesToShow: 3
        }
      },
      {
        breakpoint: 768,
        settings: {
          slidesToShow: 1
        }
      }
    ]
  });}

function call:

initPartnersSlider('#partners-slider');

Problem here is $partnersSlider.length is always 0.

As per my understanding, the html element is placed inside a minified file by webpack (prod)

main.bundle.js

I am referring my external javascript file inside index.html as a script tag. It doesnt seem to recognise the dom element with id="properties-slider" as the element is inside main.bundle.js?. I am able to debug and see it in my library code.

Has anyone done that before? Thanks for any help!

A probable solution to this problem is having a settimeout before calling methods. If there are better solutions please post.

setTimeout(() => {
     initPartnersSlider('#partners-slider');
    }, 0);

Not very convincing, but worked for me.

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