Aki
Aki

Reputation: 751

Working with Polymer and requirejs

In an attempt to create polymer elements that use requirejs modules I ran into a blocking issue. I understand that polymer is not designed to work with requirejs, but for the time being It is my only option.

Searching for answers I found two solutions:

Since I have to use require, at least for the time being, I went with the solution no.2. However, it turns out the solution causes asynchronous delays of element registration and incorrect data binding prior to Polymer upgrading the element.

Digging deeper into this issue, I started hacking undocumented Polymer internals with an intention to stop Polymer entirely until requirejs does its thing. Here is what I came up with:

Polymer.require = function(tag, deps, func) {
    var stopper = {}
    Polymer.queue.wait(stopper);
    require(deps, function() {
        delete stopper.__queue;
        Polymer.queue.check();
        Polymer(tag, func.apply(this, arguments));
    });
};

I know this is terribly wrong. Is there a better solution?

Upvotes: 6

Views: 2301

Answers (2)

Renaud
Renaud

Reputation: 4668

So there's this solution from Scott Miles but I find it a bit simplistic and inflexible as it relies on:

  • <script> tags to be executed in order, therefore ruling out:
    • async script tags
    • xhr based script loading
  • polymer getting loaded from a <script> tag, therefore:
    • layout.html and associated css won't be loaded
    • any future call to polymer.html won't be deduped

If you want more control over your bootstrapping logic you will need to enforce some amount of synchronisation between your components (which is what both requirejs and polymer are competing to do) before those are fully loaded.

The previous example is a more declarative (read polymer) way of doing things but falls short of fine grained tuning. I've started working on a repository to show how you can fully customise your load ordering, by using a more imperative approach where requirejs is given priority to orchestrate the rest of the bootstrapping.

At the time of writing, this extra control comes at the price of worse performance as the various scripts can't be loaded in parallel but I'm still working on optimising this.

Upvotes: 0

Shaun Netherby
Shaun Netherby

Reputation: 51

I found that if I embed the call to require within the Polymer script I avoid this issue.

<link rel="import" href="../polymer/polymer.html"/>
<script src="../requirejs/require.js"></script>
<script src="../something/something.js"></script>

<polymer-element name="some-component">
    <template>...</template>
    <script>
     (function() {
       Polymer('some-component', {
            someMethod: function () {

               require(['something'], function (Something) {
                    var something = new Something();
                    ...
               }
        }
     )();
    </script>
</polymer-element>

Upvotes: 4

Related Questions