With the importHref(href, onload, onerror) we can import an HTML document dynamically.
But we only can pass one file. There is an option to import multiple files? If not, what would be the best way?
Depends on what you want to do, want to load them all async and then do onload, iterate each file and onload or what? Some ideas...
Polymer.importHrefs = (files, onload, onerror) =>
files.forEach((file, i, files) =>
Polymer.importHref(file, onload, onerror));
Or async with break onerror:
Polymer.importHrefs = (files, onload, onerror, i = 0) =>
Polymer.importHref(file, (i === files.length - 1) ? onload : Polymer.importHrefs(files, onload, onerror, i + 1), onerror);
I would wrap importHref in Promises though...
Promise.all handles this nicely:
function importHref(href) {
return new Promise((resolve, reject) => {
Polymer.Base.importHref(href, function(e) {
resolve(e.target);
}, reject, true);
});
}
// Usage
Promise.all([
importHref('/elements.html'),
importHref('/elements2.html'),
importHref('/elements3.html')
]).then(values => {
values.forEach(val => console.log(val.import));
}, e => console.error(e));
http://jsbin.com/kazodirula/edit?html,output
Note: I'm using the new 4th arg to async on Polymer.Base.importHref. That will async load the import but isn't in a release yet.
Thank you to both!
Hi @ebidel ,
I tried your solution to import multiple elements. But facing issue with rest of the element apart from first element in array.
Other elements are giving error "$" undefined for "this.$.*" , whenever accessing inside that Polymer element.
It will be great help if you have any solution for this.
"Uncaught TypeError: Cannot read property 'somefuntion' of undefined"
Most helpful comment
Promise.allhandles this nicely:http://jsbin.com/kazodirula/edit?html,output
Note: I'm using the new 4th arg to
asynconPolymer.Base.importHref. That will async load the import but isn't in a release yet.