1

I am adding dynamically 2 style sheets in a WKWebView having local content loaded using loadFileURL.

The cocoa application calls the following javascript snippet to add the stylesheets.

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.type = 'text/css';
link.title = csstype;
link.href = cssSheetPath1;
document.head.appendChild(link);

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.type = 'text/css';
link.title = csstype;
link.href = cssSheetPath2;
document.head.appendChild(link);

The 2 stylesheets are located in the same directory. I can either load the first one or the second one, but never both. If I try to load both, only the first one is applied.

Any idea from where the issue can come from?

AP.
  • 5,205
  • 7
  • 50
  • 94

1 Answers1

1

You have to run that twice. Make a function and then call it for both stylesheets.

const createLink = (cssSheetPath) => {
    const link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.type = 'text/css';
    link.href = cssSheetPath;
    document.head.appendChild(link);
}

createLink('style1.css');
createLink('style2.css');

added a running code example: codesandbox example


If you dont use a function, then you should try to use two different var names:

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.type = 'text/css';
link.title = csstype;
link.href = cssSheetPath1;
document.head.appendChild(link);

var link1 = document.createElement('link');
link1.setAttribute('rel', 'stylesheet');
link1.type = 'text/css';
link1.title = csstype;
link1.href = cssSheetPath2;
document.head.appendChild(link1);

I can't test it with WKWebView.

d-h-e
  • 2,478
  • 1
  • 10
  • 18
  • This is exactly what I am doing and what is not working hence my question. – AP. Mar 23 '19 at 17:29
  • you define only one link element in your example. So, you overwrite it, when you try to use this element for two stylesheets. – d-h-e Mar 23 '19 at 17:33
  • Thanks, I know that it works in a browser. My issue is with the WKWebView where it only one for the first one. (If I swap them, as well) – AP. Mar 23 '19 at 17:48
  • issue remains the same – AP. Mar 23 '19 at 18:58
  • 1
    i found this -> [SO answer](https://stackoverflow.com/a/33126467/10921798). Maybe it helps. – d-h-e Mar 23 '19 at 19:07