6

I'm using gwt 2.3.0 in my project. I need to change my css source:

<link type="text/css" rel="stylesheet" href="gxt/css/gxt-all.css">

during run time (i want to decide which file to use on onModuleLoad method). what is the best wat to do so?

3 Answers 3

12

To inject a CSS file, you need to proceed in a similar way as ScriptInjector does for javascript file :

/** Load CSS file from url */
public static void loadCss(String url){
    LinkElement link = Document.get().createLinkElement();
    link.setRel("stylesheet");
    link.setHref(url);
    nativeAttachToHead(link);
}

/**
 * Attach element to head
 */
protected static native void nativeAttachToHead(JavaScriptObject scriptElement) /*-{
    $doc.getElementsByTagName("head")[0].appendChild(scriptElement);
}-*/;

@jusio:

StyleInjector.inject(...) works with CSS content only :

StyleInjector.inject(".myClass{color:red;}");
Sign up to request clarification or add additional context in comments.

1 Comment

Looks like I failed twice with this question (first providing wrong solution, second - forgetting to fix it). Thank you for posting correct solution.
1

Using Elemental 2 on GWT 2.8.2 or J2CL:

 public static void loadCss(String url){
        HTMLDocument document = DomGlobal.document;

        Element link = document.createElement("link");
        link.setAttribute("rel", "stylesheet");
        link.setAttribute("type", "text/css");
        link.setAttribute("href", url);

        document.getElementsByTagName("head").getAt(0).appendChild(link);
    }

Comments

0

Use this JSNI method and call this method form onModuleLoad() of GWT by giving url (path of your css) as argument based on your requirement.

public static native void loadCss(String url)/*-{
    var fileref=document.createElement("link");
    fileref.setAttribute("rel","stylesheet");
    fileref.setAttribute("type","text/css");
    fileref.setAttribute("href",url);
    $doc.getElementsByTagName("head")[0].appendChild(fileref);
}-*/;

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.