Possible to ajax load only the <page/> instead of everything of an HTML document?

给你一囗甜甜゛ 提交于 2019-12-13 04:44:49

问题


I need to

  1. On page a, when clicking the link to page b, ajax injects the of b, not refreshing the whole page
  2. Now on page b, pressing a certain reload button refreshes the whole page, with some js being run
  3. 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.

  • data attribute:

    <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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!