Skip to content

Commit

Permalink
Use HTMLImports.whenReady for detecting HTML import loading
Browse files Browse the repository at this point in the history
When using the v1 polyfills, Polymer depends on the load event for some
internal bookkeeping. This means that we cannot start using an imported
web component if our load listener is registered before Polymer's load
listener. Instead, we can use the HTMLImports.whenReady callback since
it's fired only after Polymer has had a chance to register everything.

Fixes vaadin/flow-demo#203
  • Loading branch information
Legioth committed Mar 20, 2017
1 parent c149ef7 commit 31f1501
Showing 1 changed file with 42 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.vaadin.client;

import com.google.gwt.core.client.Duration;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.user.client.Timer;
Expand Down Expand Up @@ -125,6 +126,9 @@ public interface ResourceLoadListener {

private Registry registry;

private final boolean supportsHtmlWhenReady = GWT.isClient()
&& supportsHtmlWhenReady();

/**
* Creates a new resource loader. You should not create you own resource
* loader, but instead use {@link Registry#getResourceLoader()} to get an
Expand Down Expand Up @@ -275,21 +279,56 @@ public void loadHtml(final String htmlUrl,
linkTag.setAttribute("rel", "import");
linkTag.setAttribute("href", url);

addOnloadHandler(linkTag, new ResourceLoadListener() {
class LoadAndReadyListener
implements ResourceLoadListener, Runnable {
private boolean errorFired = false;

@Override
public void run() {
// Invoked through HTMLImports.whenReady
if (!errorFired) {
fireLoad(event);
}
}

@Override
public void onLoad(ResourceLoadEvent event) {
fireLoad(event);
if (!supportsHtmlWhenReady) {
assert !errorFired;
fireLoad(event);
}
}

@Override
public void onError(ResourceLoadEvent event) {
assert !errorFired;
errorFired = true;
fireError(event);
}
}, event);
}
LoadAndReadyListener listener = new LoadAndReadyListener();

addOnloadHandler(linkTag, listener, event);
getHead().appendChild(linkTag);

if (supportsHtmlWhenReady) {
addHtmlImportsReadyHandler(listener);
}
}
}

private static native boolean supportsHtmlWhenReady()
/*-{
return !!($wnd.HTMLImports && $wnd.HTMLImports.whenReady);
}-*/;

private static native void addHtmlImportsReadyHandler(Runnable handler)
/*-{
$wnd.HTMLImports.whenReady($entry(function() {
handler.@Runnable::run()();
}));
}-*/;

/**
* Adds an onload listener to the given element, which should be a link or a
* script tag. The listener is called whenever loading is complete or an
Expand Down

0 comments on commit 31f1501

Please sign in to comment.