Can Django be used to include CSS (the tricky part here) from a JS file?

As far as I know, there is no way to use {% include%} in a dynamic JS file to include styles. But I don't want another call to the server to load the styles.

Perhaps it would be possible by taking a stylesheet and injecting it into the document's title element ... has anyone done this before?

+1


source to share


3 answers


In your JS file:

var style = document.createElement('link');
style.setAttribute('rel', 'stylesheet');
style.setAttribute('type', 'text/css');
style.setAttribute('href', 'style.css');
document.getElementsByTagName('head')[0].appendChild(style);

      



Hope it helps.

+4


source


With jquery ...



$('head').append($('<link rel="stylesheet" type="text/css" href="style.css">'))

      

+1


source


I can imagine cases where you want to dynamically generate JS or CSS, but usually you are better off creating static files for each and making your code generic enough to suit all your needs.

This goes beyond the simple question of code reuse - if you generate any of these dynamically, it will need to be reloaded every time it is used. You're wasting CPU time generating templates and wasting bandwidth by sending the same (or possibly the same) data over the cable over and over again.

But if you have a good use case for metacoding, there is no reason why you cannot:

a) put JS or CSS in the header (or body, in case of JS) of your rendered template b) create a view for JS or CSS and use Django's templating engine to render them.

The {% include%} tag works great for (a), and for (b) you just use normal HTML to link to your view URL.

0


source







All Articles