Javascript - Dynamically load a fragment of HTML and run script
I'm building a webpage and I want to re-use some HTML I have elsewhere on my website. The page I am building (index.html
)开发者_开发问答 can dynamically get and insert the HTML I want (existing.html
) using XMLHttpRequest
. However, the HTML I want to get is populated by some Javscript. That Javascript is not being executed when I load it into my new page:
index.html:
<html>
<head>
<script type = "text/javascript">
... //use XMLHttpRequest to load existing.html
initExistingHTML(); //this is function which populates loaded HTML, is not executed
</script>
</head>
<html>
existing.html:
<div>
<script type = "text/javascript">
function initExistingHTML() {
... // do some stuff
}
</script>
</div>
How can I load existing.html
and run the script which populates it?
Once the page has loaded, add in existing.html
via innerHTML
. Rather than calling its functions, just let existing.html
's code execute, which will do the same as if it were in the onload
section.
EDIT: Or, you could just correct that typo you have. initExistingHTML
!= initExistingHtml
.
lol
精彩评论