问题
I need to
- On page a, when clicking the link to page b, ajax injects the of b, not refreshing the whole page
- Now on page b, pressing a certain reload button refreshes the whole page, with some js being run
- The js must not be loaded more than once
Method X) is the standard way, which satisfies 1,2 but not 3. Alert is seen after clicking the link to page b.
a.html
<before_page>
<script>alert('abc')</script>
</before_page>
<page>
<a href=b.html>b</a>
</page>
<after_page/>
-
b.html
<before_page>
<script>alert('abc')</script>
</before_page>
<page/>
<after_page/>
Method Y) satisfies 1,3 but not 2.
a.html
<before_page>
<script>alert('abc')</script>
</before_page>
<page>
<a href=c.html>c</a>
</page>
<after_page/>
-
c.html
<!--nothing before <page/> -->
<page/>
<!-- nothing after <page/> -->
The question is how to satisfy all 1,2,3?
回答1:
Easy option to satisfy all scenarios is to cache external pages and place code inside each page's div. There are two ways to cache pages, either using data attribute for each page, or enable it globally.
dataattribute:<div data-role="page" data-cache-dom="true" id="pageID"> <!-- JS code / libraries --> </div>Globally
<script src="jquery.js"></script> <script> $(document).on("mobileinit", function () { $.mobile.page.prototype.options.domCache = true; }); </script> <script src="jquery-mobile.js"></script>
Another option in case you don't want to cache pages, it is preferable to place all JS libraries, code and style sheets in head of each and every page. They will be loaded once only. External pages are removed once hidden, placing code in page div will load same code again and again.
$(document).on("pagecreate", "#pageID", function () {
$(".selector").on("event", function () {
/* code */
});
});
Demo
来源:https://stackoverflow.com/questions/27163438/possible-to-ajax-load-only-the-page-instead-of-everything-of-an-html-document