Execute page-specific javascript code after PJAX success

血红的双手。 提交于 2019-12-11 01:08:17

问题


Here's my conundrum:

My website uses PJAX to load HTML into the '#main' container for each page.

Each page has its own specific javascript file. E.g: 'dashboard.index.js', 'inbox.index.js' and so on. Note: All libraries are preloaded on the first load of the page through PreloadJS to avoid javascript compilation overhead.

The first load of the page is perfect, no worries, since it is a normal HTML load.

However if i come back to this page again, PJAX won't reload the javascript file, given it's already in the DOM.

What i tried so far & didn't work perfectly:

  1. Place javascript file at the bottom of 'main' container. PJAX transfers it to the 'HEAD' of the DOM and won't load it the second time around.
  2. Place in-line scripts in the 'main' container to execute functions of each page. Fails since the code is executed before JS libraries are loaded.
  3. Bind 'PJAX success' event and execute function. Unable to determine which function to execute based on current loaded page.

Hence, my question:

Is there any strategy to load specific javascript files associated to each page?


回答1:


When loading HTML from pjax, i added a 'data-js' attribute to the div, which contained the name of the function to call upon successfully loading HTML.

Then it was just a matter of using the 'pjax:success' event to call the function.



来源:https://stackoverflow.com/questions/24927369/execute-page-specific-javascript-code-after-pjax-success

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