Skip to content

Commit

Permalink
feat(element): add option to avoid styles injecting
Browse files Browse the repository at this point in the history
  • Loading branch information
nolimits4web committed Jan 16, 2023
1 parent ea8bfbe commit 2291ec8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/element/swiper-element.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
declare const SwiperContainer: HTMLElement;
declare const SwiperSlide: HTMLElement;
declare const register: () => void;
declare const register: (injectStyles: boolean) => void;

export { register, SwiperContainer, SwiperSlide };
30 changes: 22 additions & 8 deletions src/element/swiper-element.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { updateSwiper } from '../components-shared/update-swiper.js';

//SWIPER_STYLES

let globalInjectStyles = true;

const addGlobalStyles = (preInit, swiper) => {
let globalStyles = document.querySelector('style#swiper-element-styles');
const shouldOverwrite = globalStyles && globalStyles.preInit && !preInit;
Expand Down Expand Up @@ -49,7 +51,7 @@ class SwiperContainer extends ClassToExtend {

cssStyles() {
return [
SwiperCSS, // eslint-disable-line
globalInjectStyles ? SwiperCSS : '', // eslint-disable-line
...(this.modulesStyles && Array.isArray(this.modulesStyles) ? this.modulesStyles : []),
].join('\n');
}
Expand All @@ -59,12 +61,19 @@ class SwiperContainer extends ClassToExtend {
}

render() {
// global styles
addGlobalStyles(false, this);
if (globalInjectStyles) {
// global styles
addGlobalStyles(false, this);
}

// local styles
this.stylesEl = document.createElement('style');
this.stylesEl.textContent = this.cssStyles();
this.shadowEl.appendChild(this.stylesEl);
const localStyles = this.cssStyles();
if (localStyles.length) {
this.stylesEl = document.createElement('style');
this.stylesEl.textContent = localStyles;
this.shadowEl.appendChild(this.stylesEl);
}

this.cssLinks().forEach((url) => {
const linkExists = document.querySelector(`link[href="${url}"]`);
if (linkExists) return;
Expand Down Expand Up @@ -232,9 +241,14 @@ class SwiperSlide extends ClassToExtend {
}

// eslint-disable-next-line
const register = () => {
const register = (injectStyles = true) => {
if (typeof window === 'undefined') return;
addGlobalStyles(true);
if (!injectStyles) {
globalInjectStyles = false;
}
if (globalInjectStyles) {
addGlobalStyles(true);
}
if (!window.customElements.get('swiper-container'))
window.customElements.define('swiper-container', SwiperContainer);
if (!window.customElements.get('swiper-slide'))
Expand Down

0 comments on commit 2291ec8

Please sign in to comment.