Question

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?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top