开发者

Running Javascript from external file loaded with AJAX

I've been trying to get this sorted all day, but reall开发者_开发问答y 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.


If you fetch html via Ajax, and that html has a <script> tag in it, and you write that html into your document via something like $('#foo').append(html), then the JS should run immediately without any hassle whatsoever.


jquery automatically processes scripts received in an ajax request when adding the content to your page. If you are having a particular problem then post some code.

See this link

dataType: "html" - Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜