从装载了AJAX外部文件运行的JavaScript [英] Running Javascript from external file loaded with AJAX

查看:104
本文介绍了从装载了AJAX外部文件运行的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图让这个排序的所有日子,但真的无法弄明白。我有与 < D​​IV ID =AJAX>< / DIV> 的填充关闭一个标签式菜单拉在存储在外部文件HTML code段,其中包含一些JavaScript(主要是表单验证)。

我见过的,我需要的eval()的code的地方,但对事物的相同身边的人说,它的最后一件事。

有人能指出我在正确的方向,如果可能的话提供了一个例子,因为我很新的jQuery / JavaScript的。

非常感谢:)

解决方案
  

拉​​动存储在外部文件HTML code片段包含一些JavaScript(主要是表单验证)。

避免这样做。写<脚本> 的innerHTML 不会导致脚本被执行...虽然事后移动元素的可以的导致其得到执行,在不同的时间在不同的浏览器。

所以,这在实践中不符,它并没有真正任何意义无论如何要包括脚本:

  • 在加载相同的片断两次,你会运行相同的脚本的两倍,这可能会重新定义一些绑定到页面的函数或变量,它可以让你在非常奇怪的和难以于─调试情况

  • 非异步/推迟脚本期待在分析时运行,并可能包括文件撰写时插入到现有文档(以的情况下不能正常工作的技术这通常会破坏整个页面,当试图加载第三方广告/跟踪脚本)一种常见的症状。

是的,jQuery的的尝试的做一些这方面的提取脚本元素和执行这些浏览器之间更加一致。但是,没有,它不设法解决所有的情况(并原则不能)。所以,不要问它。保持你的脚本的静态和运行需要发生在负载回调任何有约束力的脚本code。

I've been trying to get this sorted all day, but really cant figure it out. I've got a page with
<div id="ajax"></div> that is populated off a tab based menu pulling in a snippet of HTML code stored in an external file that contains some javascript (mainly form validation).

I've seen in places that I need to eval() the code, but then on the same side of things people say its the last thing to do.

Can someone point me in the right direction, and provide an example if possible as I am very new to jQuery / JavaScript.

Many thanks :)

解决方案

pulling in a snippet of HTML code stored in an external file that contains some javascript (mainly form validation).

Avoid doing this. Writing <script> to innerHTML doesn't cause the script to get executed... though moving the element afterwards can cause it to get executed, at different times in different browsers.

So it's inconsistent in practice, and it doesn't really make any sense to include script anyway:

  • when you load the same snippet twice, you'd be running the same script twice, which might redefine some of the functions or variables bound to the page, which can leave you in extremely strange and hard-to-debug situations

  • non-async/defer scripts are expecting to run at parse time, and may include techniques which can't work when inserted into an existing document (in the case of document.write this typically destroys the whole page, a common symptom when trying to load third-party ad/tracking scripts).

Yes, jQuery tries to make some of this more consistent between browsers by extracting script elements and executing them. But no, it doesn't manage to fix all cases (and in principle can't). So don't ask it to. Keep your scripts static, and run any binding script code that needs to happen in the load callback.

这篇关于从装载了AJAX外部文件运行的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆