shubhamjain / svg-loader

Plug 'n Play external SVG loader
MIT License
192 stars 20 forks source link

cannot find elements from document query selector #12

Closed sarunluitel closed 2 years ago

sarunluitel commented 2 years ago

I am using this library and need to get a reference of an inner element from svg. If the javascript waits a certain time after the dom is loaded, I can get the elements through document.selectElementByXXX. If the selector runs sequentially, if returns undefined

there is a time difference which makes sense as the svg is being "mounted". is it possible for there to be a "loadCompleted" Event to where we can guarantee the element being there?

Thank you

shubhamjain commented 2 years ago

I have added an event iconload that you can use in the latest version to get reference to the mounted SVG element.

Documentation: https://github.com/shubhamjain/svg-loader#event

sarunluitel commented 2 years ago

Thank You!

I got the latest version and followed the docs but the event is not firing. I tried both adding event listener on window and setting oniconload.

I am using this on a nuxt.js project. Also tried the this.$refs.elementName (similar to your react example on the docs) to add the event but still nothing happens.

There is no error message to show. let me know if you need any further information.

shubhamjain commented 2 years ago

@sarunluitel Can you show me your code?

sarunluitel commented 2 years ago

I implemented different ways and none of them are firing events. 1)

        <svg @iconload="updateNotification"
          ref="notificationIcon"
          data-cache="disabled"
          data-src="/path/t0/svg.svg"
          class="navigationButton"></svg>

2)

    window.addEventListener('iconload', () => {
      console.log('event from window event listener iconload');
      this.updateNotification();
    });

3)

    this.mailIconSvg = this.$refs.notificationIcon;
    // Doing console.log on this step returns the dom element of SVG
    if (this.mailIconSvg) {
      this.mailIconSvg.oniconload = () => { console.log('event from oniconload'); this.updateNotification() }
    }
sarunluitel commented 2 years ago

It is now working. I changed the import import 'external-svg-loader'; to import 'external-svg-loader/dist/svg-loader.js';

and it's working properly as intended

I think the issue is that the dist/svg-loader.min.js has not been minified with the latest code version. and this is the file set as main on package.json. Hope fixing this solves the issue

shubhamjain commented 2 years ago

@sarunluitel Thanks for your input. I had to run npm run build before publishing the package to create svg-loader.min.js. Probably makes sense to create a script for this. But I encountered npm auth errors while doing so. Let's solve that later.

sarunluitel commented 2 years ago

Thank you. This event is crucial to make any transformation through javascript on the svg elements. glad to help!