简体   繁体   English

通过动态注入JavaScript依赖项<script> tag

[英]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. 通过在src创建<script>标签在原始JavaScript中使用JSONP,使我考虑在JavaScript插件和其他利用库但希望尽可能独立的JavaScript组件中使用相同的方法进行依赖项注入。

Using jQuery as an example of a popular library that could potentially need to be injected... 使用jQuery作为可能需要注入的流行库的示例...

// 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? 确实在这一点上它主要是概念性的( 但确实可行 ),但是我想知道这是否可以视为JavaScript依赖项注入的可接受解决方案? 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. 在构建用于外部网站的Web插件时,请尝试强制开发人员包括所需的库。 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. 关于您的示例:将代码放在一个(匿名)函数中,以免用不必要的变量填充全局范围。

是的,我相信这是google.load()背后的概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM