简体   繁体   中英

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)?

Consider this approach (for simplicity, I will consider jQuery):

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

Let's assume that the returned html contains something as such:

<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).

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?

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). 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).

Actually Safari and Internet Explorer (and most likely others) won't execute <script> 's that are injected through Ajax as a security measure.

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. Attach a callback listener to your script loader and execute all code in the callback, not in the external .js file itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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