简体   繁体   中英

Best practices to load HTML + Javascript dynamically

I have a page that loads (using a XHR request) a modal box with a form inside.

The form is composed by HTML tags + some Javascript to do validation and to submit it (using another XHR request).

I did that, and it already works, but the resulting DOM is ugly, because the script tag is inside the modal, like in this simplified example:

<html>
<head>...</head>
<body>
<div id="modal"> 
    <form>...</form> <!-- This is my dynamically loaded HTML -->
    <script>...</script> <!-- This is the dynamically loaded JS -->
</div>
<script>...</script> <!-- My main scripts -->
</body>
</html>

I have two questions about this:

1) The best practice is to put all JS code right before body closes, but when I do my dynamic loading, I end up with JS inside the modal div. Is there an efficient way to load only HTML to the div and inject the JS at the end of body ? Are there any tools for that? Or should I not worry about it?

2) I'm using jQuery, so I try to use $(document).ready() for all JS code, but if I use this for modal JS, it won't run, probably because the event is not triggered a second time. Is there any event I can use to make my dynamically loaded JS to run after laoding is complete? Or should I just put it in the end?

Answer to both questions:

I don't see a reason why you shouldn't insert the JS scripts in the DOM inside the modal. I think it's even better that way compared to a global place where you put all the injected scripts. This way you will still know which modal loads which script.

And it solves your second problem as well. When you first insert your DOM nodes and then the <script> element that will work on them, you don't need to wait for a ready event.

Only other way I can think of is having the modal scripts available globally, loading the modal and then doing something like ModalScript.initialize("#modal") .

You could use a framework like Browserify to bundle and dynamically load ("lazy load") resources as needed.

This is a good example/tutorial.

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