4

I want to create a tag for a carousel, but I only want to load the CSS and Javascript files when this tag is used on the site, but I can only make it work if I add it to the <body> of my website.

Is there a way to only load is in the tag?

my tag example (that only works if I move the css and .js files into the website body:

<carousel>
  <div class="row" hide="{$gg.filterApplied || $gg.redeem.redeemInProgress()}">
    <div class="col-sm-12">
      <div class="logos text-center">
        <div class="divider"></div>
        <div data-slick='{"slidesToShow": 4, "slidesToScroll": 4}'>
          <div><h3>1</h3></div>
          <div><h3>2</h3></div>
          <div><h3>3</h3></div>
          <div><h3>4</h3></div>
          <div><h3>5</h3></div>
          <div><h3>6</h3></div>
        </div>
        <div class="divider"></div>
      </div>
    </div>
  </div>

  <style scoped>
    @import url("//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css")
  </style>

  <script src="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js"></script>
  <script>
    var self = this;
    self.mixin(SharedMixin)
  </script>
</carousel>
balexandre
  • 73,608
  • 45
  • 233
  • 342
  • Did you ever make any progress on this? Got the same question! – abigwonderful Oct 21 '16 at 16:35
  • @abigwonderful unfortunately not, what I ended up doing was use `gulp-concat-vendor` and concat all vendor js and css into a js and a css file ... not the best approach but I did not find any help out there for my question and I had to do something useful ... – balexandre Oct 21 '16 at 17:29
  • gotcha - turns out the project I'm working on has it's own protocol for dealing with this situation. Would love to find a better way as well! – abigwonderful Oct 25 '16 at 17:16

1 Answers1

1

I had a similar problem and I solved in this way.

I added a method to tags, using a mixin, to load resources at runtime and I call it before-mount is fired, passing a list of css and js files.

It uses the function getScript of jQuery.

loadResources(css, js, callback){
    for(var i = 0; i < css.length; i++){
        if(css[i] !== ''){
            var link = document.createElement('link');
            link.setAttribute("rel", "stylesheet");
            link.setAttribute("type", "text/css");
            link.setAttribute("href", css[i]);
            document.getElementsByTagName("head")[0].appendChild(link);
        }
    }
    var jsProgress = 0;
    for(var j = 0; j < js.length; j++){
        $.getScript(js[j], function () {
            if (++jsProgress == js.length && typeof callback !== 'undefined') callback();
        });
    }
}
alcaprar
  • 739
  • 8
  • 18