简体   繁体   English

动态加载HTML + Javascript的最佳实践

[英]Best practices to load HTML + Javascript dynamically

I have a page that loads (using a XHR request) a modal box with a form inside. 我有一个页面加载(使用XHR请求)具有内部表单的模式框。

The form is composed by HTML tags + some Javascript to do validation and to submit it (using another XHR request). 该表单由HTML标记+一些Javascript组成,以进行验证和提交(使用另一个XHR请求)。

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: 我这样做了,它已经可以工作了,但是生成的DOM很丑陋,因为script标记位于模式内部,如下面的简化示例所示:

<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. 1)最佳做法是将所有JS代码直接放在body关闭之前,但是当我进行动态加载时,最终在模态div中使用JS。 Is there an efficient way to load only HTML to the div and inject the JS at the end of body ? 有没有一种有效的方法可以只将HTML加载到div并将JS注入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. 2)我使用的是jQuery,所以我尝试对所有JS代码使用$(document).ready() ,但是如果我将其用于模式JS,它将无法运行,可能是因为该事件未在第二秒触发时间。 Is there any event I can use to make my dynamically loaded JS to run after laoding is complete? 在完成Laoding之后,是否可以使用任何事件使动态加载的JS运行? 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. 我看不出为什么不应该在modal内的DOM中插入JS脚本的原因。 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. 当您首先插入DOM节点,然后再插入将在其上工作的<script>元素时,无需等待就绪事件。

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") . 我能想到的唯一其他方法是使模态脚本全局可用,加载模态脚本,然后执行类似ModalScript.initialize("#modal")

You could use a framework like Browserify to bundle and dynamically load ("lazy load") resources as needed. 您可以使用Browserify之类的框架来根据需要捆绑和动态加载(“延迟加载”)资源。

This is a good example/tutorial. 是一个很好的示例/教程。

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

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