My Javascript code is rendered twice when SPA is enabled
How To articles are not official guidelines or officially supported documentation. They are community-contributed content and may not always reflect the latest updates to Liferay DXP. We welcome your feedback to improve How To articles!
While we make every effort to ensure this Knowledge Base is accurate, it may not always reflect the most recent updates or official guidelines.We appreciate your understanding and encourage you to reach out with any feedback or concerns.
Legacy Article
You are viewing an article from our legacy "FastTrack"
publication program, made available for informational purposes. Articles
in this program were published without a requirement for independent
editing or verification and are provided"as is" without
guarantee.
Before using any information from this article, independently verify its
suitability for your situation and project.
Issue
- The following code renders a modal window when the DOM Content is loaded:
...
if (document.readyState === 'loading'){
document.addEventListener("DOMContentLoaded", onContentLoaded);
} else {
onContentLoaded();
}
...
- Navigate around the pages of the site.
- The modal will be loaded twice eventually since the method onContentLoaded will be executed more than one time since the module Liferay SPA also use the event
DOMContentLoaded
to load itself.
- If Liferay SPA is loaded after the load of the custom code, then the modal will be displayed twice since Liferay SPA logic will re-render the page with the elements present at this time.
-
This happens because if the custom code has already included its markup and registered its events, Liferay SPA will remove them and it will load them again since it considers that it is still the new navigation.
Environment
Resolution
- In order to prevent this situation, the custom code should be adapted to be executed after Liferay SPA is fully loaded. The following could be a possible approach:
if (Liferay && Liferay.SPA) {
Liferay.on('SPAReady', function() {
// The custom logic
});
}
-
For this example to be effective, the custom code should be placed after the line
<@liferay_util["include"] page=top_head_include />
of the file portal_normal.ftl
. If this is not guaranteed, the Liferay object might not have been defined.
Did this article resolve your issue ?