Last active
December 23, 2015 02:09
-
-
Save zaphar/6564897 to your computer and use it in GitHub Desktop.
A polymer custom element that can load requirejs modules. You may have to modify the paths to suite your setup.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<polymer-element name="require-js" attributes="libnames event"> | |
<script> | |
(function() { | |
// Helper function to add a script. | |
var addScript = function(src) { | |
var script = document.createElement('script'); | |
script.src = src; | |
var s = document.querySelector('script'); | |
s.parentNode.insertBefore(script, s); | |
return script; | |
}; | |
// Add the requireScript to the dom. | |
var requireScript = addScript("/js/require-jquery.js"); | |
requireScript.onload = function() { | |
// Once the require script has loaded then configure our base url | |
require.config({ | |
baseUrl: "/js/" | |
}); | |
// And construct the polymer element. | |
Polymer('require-js', { | |
// space seperated list of libs to load using requirejs | |
libnames: "", | |
// name of the event to fire when the libs are loaded. | |
event: "require-js-loaded", | |
created: function() { | |
var self = this; | |
// the below only makes sense if there is a non-empty libnames | |
if (self.libnames != "") { | |
// Split the list and pass that as an argument to the require function | |
var libList = self.libnames.split(" "); | |
require(libList, function() { | |
var libs = {}; | |
// marshall the returned libs into a container | |
for (idx in libList) { | |
libs[libList[idx]] = arguments[idx]; | |
} | |
// fire the event method with the libs as a payload | |
self.fire(self.event, {libs: libs}) | |
}); | |
} | |
} | |
}); | |
}; | |
})(); | |
</script> | |
</polymer-element> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment