问题
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:
- 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.
- 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.
- 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