Reputation: 294
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?
Upvotes: 2
Views: 1936
Reputation: 337560
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.
Upvotes: 1
Reputation: 93
You can try this
$(document).ready(function(){
$('head').append('<link rel="stylesheet" href="https://myurl/OwlCarousel/dist/assets/owl.carousel.css" type="text/css" />');
});
Upvotes: -1