简体   繁体   English

延迟加载JavaScript的最佳做法

[英]Best practice for lazy loading in JavaScript

What's the best way to dynamically load HTML content and inject it in the page (when the HTML contains both <script src="..." /> tags and function calls to those scripts)? 动态加载HTML内容并将其注入页面的最佳方法是什么(当HTML同时包含<script src="..." />标记和对这些脚本的函数调用时)?

Consider this approach (for simplicity, I will consider jQuery): 考虑这种方法(为简单起见,我将考虑使用jQuery):

<script>
$.ajax({
    url: 'http://...',
    success: function(html) {
        $("body").append(html);
    }
});
</script>

Let's assume that the returned html contains something as such: 假设返回的html包含以下内容:

<script src="some_script.js"></script>
<script>
some_function(); // function defined in some_script.js
</script>

Since some_function() is defined in some_script.js it will be available only after some_script.js was loaded but (usually) it will be executed before some_script.js will be loaded (thus causing an error). 由于some_function()是在some_script.js中定义的,因此只有在some_script.js加载后才可用,但(通常)它将在some_script.js加载之前执行(从而导致错误)。

Obviously, there are some solutions to overcome this issue, but what is the best practice in this case? 显然,有一些解决方案可以解决此问题,但是这种情况下的最佳实践是什么? Should libraries such as RequireJS be used instead? 应该改用诸如RequireJS之类的库吗?

The example above is a result of the pattern I use: I have a component which I will load only when it's going to be used (at that point I make an Ajax call to retrieve both the HTML and the required scripts). 上面的示例是我使用模式的结果:我有一个仅在将要使用它时才加载的组件(那时,我进行Ajax调用以同时检索HTML和所需的脚本)。 Still, it can happen that many scripts are required and it's easier to write them as a set of tags in the HTML template rather than loading them through JavaScript (this is also preferred as the script URL may be generated inside the application so a plain JS script may not be aware of the absolute script URL). 尽管如此,仍然可能会需要许多脚本,并且将它们作为一组标签写在HTML模板中要比通过JavaScript加载更为容易(这也是首选方法,因为脚本URL可能在应用程序内部生成,因此使用纯JS脚本可能不知道绝对脚本URL)。

Actually Safari and Internet Explorer (and most likely others) won't execute <script> 's that are injected through Ajax as a security measure. 实际上,Safari和Internet Explorer(以及最有可能的其他浏览器)不会执行通过Ajax注入的<script>作为安全措施。

What I can recommended is that when you need a library of considerable size (yet isn't required for actual use of your web application), is to rather load the .js-file containing the library into your document after which you can use all properties and methods defined in the library. 我的建议是,当您需要一个相当大的库(但实际使用Web应用程序并不需要)时,是将包含该库的.js文件加载到文档中,之后您可以使用所有库中定义的属性和方法。 Attach a callback listener to your script loader and execute all code in the callback, not in the external .js file itself. 将回调侦听器附加到脚本加载器,并执行回调中的所有代码,而不是外部.js文件本身。

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

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