0

how I can dynamicaly load CSS file on VueJS (SPA) application?

Short scenario

  • Application starts and submit request to backend server for CSS file name by url address
  • Apllication get response from backend server with css filename params

Then i need call something whats load new CSS file by response data.

We used this for web-site branding (CSS are depends on actual domain - but site is installed on one hosting). This CSS file can be located on our server (/assets/css/xx.css) or on other servers.

Short snippet from Vue component:

loadCssRequest(location.href).then(function(reponse){
    // something whats load css by response.css_code
});

Thanks for any ideas.

1 Answer 1

1

You can inject css to head of component

loadCssRequest(location.href).then(function(reponse){
   var style = document.createElement('style');
   style.type = 'text/css';
   style.innerHTML = reponse;
   document.getElementsByTagName('head')[0].appendChild(style);
});

Or if you have css path on another server (for example /assets/css/xx.css)

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', '/assets/css/xx.css');
document.getElementsByTagName('head')[0].appendChild(link);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.