Question

I'm looking to conditionally import something with polymer. How would one build something like the following.

<html>
  <head>
  <link rel="import" href="polyfill-geolocation.html">
  </head>
  <body>
  <script>
    // I can use geo
    navigator.geolocation.getCurrentPosition(callback);
  </script>
  </body>
</html>

Where modernizr-geolocation.html would conditionally check and load.

<script>
  if (!navigator.geolocation) {
    // load the geolocation-polyfill.js
    // and defer execution of the html import till it is ready
    // then execute in order.        
  }
</script>

I don't want to download the polyfill if I don't need it and I do not want to have conditional callbacks in my main that waits for an oncomplete event. Maybe this is not possible?

Was it helpful?

Solution

defer execution of the html import till it is ready then execute in order.

If you are willing to load (and evaluate) geo-location-polyfill.js synchronously in your script tag, it will block the execution of future script tags and make your example work.

It's probably better to gate your document script on some kind of ready event however, and let things proceed asynchronously.

Some information about dynamic imports:

You can use imports dynamically by creating a <link> tag imperatively and appending it to <head>.

The import will be parsed as soon as it's loaded. The link tag will fire a load event if you want to capture load complete.

Alternatively, you can use Polymer.import method:

Polymer.import(arrayOfUrls, completionCallback);

Example:

Polymer.import(['a.html', 'b.html'], function() { // a and b have loaded now });

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top