2

I have a Jquery code append both Css and Js file to create a banner-slider with Owlcarousel.

The jquery code had appended both into html. The function .owlCarousel() work fine but the css don't. In console, it only GET the owl.carousel.js file.

The one I found most like is this I already tried but count not get it working.

Jquery

$(document).ready(function(){
        var u = document.createElement("link");
        u.type = "text/css";
        u.href = "https://myurl/OwlCarousel/dist/assets/owl.carousel.css";
        $("#lookbookslider-2").append(u);

        var t = document.createElement("script");
        t.type = "text/javascript";
        t.src = "https://myurl/OwlCarousel/dist/owl.carousel.js";
        $("#lookbookslider-2").append(t);
        $.getScript("https://myurl/OwlCarousel/dist/owl.carousel.js");

  $("#lookbookslider-2").append("html here");

});

I dont have access to html file. I can only work with my js file. How can I make the css file working? Or I have to append all the style directly?

Alok Swain
  • 6,409
  • 5
  • 36
  • 57
someoneuseless
  • 303
  • 3
  • 17

3 Answers3

1

Add to the link the rel attribute-:

 u.rel  = 'stylesheet';
suspectus
  • 16,548
  • 8
  • 49
  • 57
1

You're missing the rel attribute from the link attribute. Also note that type is not needed. Try this:

var u = document.createElement("link");
u.rel = "stylesheet";
u.href = "https://myurl/OwlCarousel/dist/assets/owl.carousel.css";
$("#lookbookslider-2").append(u);

However it's worth noting that this can be simplified if you use jQuery to create the <link /> element, and also you should append the new stylesheet reference in to the head:

var $link = $('<link />', {
  rel: 'stylesheet',
  href: 'https://myurl/OwlCarousel/dist/assets/owl.carousel.css'
}).appendTo('head');

Finally, note that appending stylesheets at runtime is a little bit of an anti-pattern. If you're trying to make the page more efficient, I'd suggest using bundling and minification of your CSS and JS, and then include all required references through HTML on page load.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
-1

You can try this

$(document).ready(function(){
$('head').append('<link rel="stylesheet" href="https://myurl/OwlCarousel/dist/assets/owl.carousel.css" type="text/css" />');
});
t hj
  • 93
  • 4