I understand that I can handle the pageinit()
or other events to execute JavaScript for a newly loaded page, but that requires me to have the actual JavaScript exist or be reference from the Main page.
How can I include scripts at the bottom of a sub page, and have it execute on load of the page?
I tried to set the sub page's function to a global variable (I know it's dirty), but even that doesn't seem to work.
I understand that I can handle the pageinit()
or other events to execute JavaScript for a newly loaded page, but that requires me to have the actual JavaScript exist or be reference from the Main page.
How can I include scripts at the bottom of a sub page, and have it execute on load of the page?
I tried to set the sub page's function to a global variable (I know it's dirty), but even that doesn't seem to work.
Share Improve this question asked Nov 17, 2011 at 16:06 John B♦John B 20.4k35 gold badges123 silver badges173 bronze badges 1- possible duplicate of jQuery mobile -loading dynamic pages – Jasper Commented Nov 17, 2011 at 20:33
2 Answers
Reset to default 6Found the answer myself. It looks like the JavaScript on the child page needs to be inside the "page", not just inside the body tag:
<body>
<div data-role="page" data-title="My Subpage">
<p>Awesome content!</p>
<!-- DO put your JavaScript here. -->
<script type="text/javascript">
alert('This works');
</script>
</div>
<!-- DON'T put your JavaScript here. -->
<script type="text/javascript">
alert('This doesn't work');
</script>
</body>
Pro tip: It looks like any script inside the body but outside the "Page" element, even on the main page (first loaded page), don't get executed!!! So even if you disabled the AJAX loading/transitions of jQuery mobile, the default page rendering still kills those scripts.
Anything you want JQM loaded needs to be inside the element, as described in their documentation.
I personally noticed memory-hogs and leaks when loading jscript this way, it seemed it never correctly removed it thus creating duplicates if this page was loaded over and over again. I finally moved that jscript to the main page, and my problems were gone! Of course this could be related to the code itself, but it was doing a lot of event binding/unbinding and I was never sure JQ actually removed blank references.
Anyway, just my $.02...