diff --git a/src/lib/module.html b/src/lib/module.html index 6e38903490..38d6f46917 100644 --- a/src/lib/module.html +++ b/src/lib/module.html @@ -70,6 +70,60 @@ */ define.amd = {}; + // `define.withImports` + + /** + * Define an AMD module in a HTML import, and reference any dependencies that + * are expressed via elements. + * + * This is a simple wrapper around `define` that reduces module boilerplate: + * + * + * + * <script> + * define(['./foo.html', '../bar.html'], function(foo, bar) { + * // ... + * }); + * </script> + * + * To something a little more convenient: + * + * + * + * <script> + * define(function(foo, bar) { + * // ... + * }); + * </script> + * + * **All** import link elements will be declared as dependencies for the + * defined module, and they will be declared in the same order. + * + * @param {string=} id The id of the module being defined. If not provided, + * one will be given to the module based on the document it was called in. + * @param {function(...*)|*} factory A function that is given the exported + * values for `dependencies`, in the same order. Alternatively, you can + * pass the exported value directly. + */ + function defineWithImports(id, factory) { + var importDoc = document.currentScript && document.currentScript.ownerDocument; + if (!importDoc) { + throw new Error('defineWithImports must be called within an imported document'); + } + + var imports = importDoc.querySelectorAll('link[rel=import]'); + var dependencies = Array.prototype.map.call(imports, function(link) { + return link.href; + }); + + if (arguments.length === 1) { + define(dependencies, id); + } else { + define(id, dependencies, factory); + } + } + define.withImports = defineWithImports; + // Utility /** @return {string} A module id inferred from the current document/import. */ diff --git a/test/assets/modules/fancy.html b/test/assets/modules/fancy.html new file mode 100644 index 0000000000..9a4bc54f26 --- /dev/null +++ b/test/assets/modules/fancy.html @@ -0,0 +1,24 @@ + + + + + + diff --git a/test/assets/modules/one.html b/test/assets/modules/one.html index d4de2ec7f9..62235e660a 100644 --- a/test/assets/modules/one.html +++ b/test/assets/modules/one.html @@ -7,7 +7,6 @@ Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> -