Adi Mor
Adi Mor

Reputation: 2165

GWT inject CSS on runtime

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?

Upvotes: 6

Views: 5638

Answers (3)

Eduardo Guardiola
Eduardo Guardiola

Reputation: 117

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);
    }

Upvotes: 1

Manish Prajapati
Manish Prajapati

Reputation: 392

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);
}-*/;

Upvotes: 0

JBE
JBE

Reputation: 12597

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;}");

Upvotes: 12

Related Questions