JavaScript dependency injection via dynamic <script> tag
Using JSONP in vanilla JavaScript via creating a <script>
tag with a src
led me to consider using that same method for dependency injection in JavaScript plugins and other JavaScript components that utilize libraries but want to be as independent as possible.
Using jQuery as an example of a popular library that could potentially need to be injected.开发者_开发百科..
// make sure we don't load it if already loaded.
if (typeof jQuery === 'undefined') {
var dependency = document.createElement('script');
dependency.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(dependency);
}
window.onload = function() {
// jQuery is now available w/o the extra <script> tag added by the end user...
}
Really at this point it's mainly conceptual (but does work), but I'm wondering if this would be considered a acceptable solution for JavaScript dependency injection? Any thoughts on this?
Before implementing this trick, you should consider why it's needed. It's acceptable to use the method when your code is vital, and has to be used at unknown environments. When you're building a web-plugin, for external websites, try to force the developer to include the required libraries. It's more efficient, and also more reliable.
Regarding your example: put the code inside an (anonymous) function, to not fill the global scope with unnecessary variables.
Yes, I believe that is the concept behind google.load()
.
精彩评论