Anto Anto - 1 year ago 87
Javascript Question

CSS file added dynamically is not loaded

I am creating a Javascript widget that uses angular and NVD3 libraries to display certain graphs. In the script file (located in the server) that contains the code for generating these graphs I have added the code for adding dynamically the script files pointing to these libraries, in addition to the CSS file (nv.d3.css) used by NVD3 to render properly its elements:


var css = document.createElement('style');
css.type = 'text/css';
css.setAttribute('src', 'http://localhost:3000/javascript/bower_components/nvd3/build/nv.d3.css');

function loadScript(address){
var angularnvd3Script = document.createElement('script');
angularnvd3Script.setAttribute('type', 'text/javascript');
angularnvd3Script.setAttribute('src', address);

When the client application embedding the widget runs, the scripts are loaded successfully, the graphs are shown correctly from a data point of view, the CSS file seems to be added correctly too in the client HTML file, yet it is not used, as the style of the graphs is not picked up. I have tried to add the file in the head instead of the body, but the same unexpected behaviour occurs.
Does anyone know where the problem may be? Thanks in advance

Answer Source

Well you're mixing two ways to add CSS to your page. You can either use the style tag or the link tag.

By using the style tag you can't use href so in your case you have to use the link approach:

var link = document.createElement('link')
link.setAttribute('rel', 'stylesheet')
link.setAttribute('type', 'text/css')
link.setAttribute('href', 'http://localhost:3000/javascript/bower_components/nvd3/build/nv.d3.css')