patrick-steele-idem / morphdom

Fast and lightweight DOM diffing/patching (no virtual DOM needed)
MIT License
3.21k stars 129 forks source link

Question : Using Morphdom with Fetch API and server rendered HTML #189

Closed ChrisJohnson-83 closed 4 years ago

ChrisJohnson-83 commented 4 years ago

Apologies if this question is too simplistic, I am just trying to understand if Morphdom would be a good use case for my scenario.

I have server rendered HTML which is returned in a promise from a Javascript Fetch API request. Sometimes the returned HTML contains only the portion that needs to be replaced in the DOM but sometimes it contains HTML which doesn't need to be replaced. Currently I update the DOM like this:

 function fetchDatatable(page, targetId) {

        const query = document.querySelector('input#query').value;
        fetch('/projects/datatable?template=false&query=' + query + '&page=' + page, {
            method: 'GET',
        })
        .then(
            response => response.text()
        )
        .then(text => {

            // select the element that will be replaced
            var currentHtml = document.querySelector(targetId);

            // get new element from response
            const parser = new DOMParser();
            const htmlDocument = parser.parseFromString(text, 'text/html');
            const newHtml = htmlDocument.documentElement.querySelector(targetId);

            // replace element
            currentHtml.parentNode.replaceChild(newHtml, currentHtml);

        });
}

Could this be a good use case for Morphdom instead? Does Morphdom have the capability to allow me to do a more intelligent DOM replacement?

snewcomer commented 4 years ago

Thanks for the issue! Yes, morphdom can be a good candidate for patching DOM at any level. You just need to make sure what you are patching is at the same level - So the first and second arguments are at the same level in the DOM tree. With targetId, I imagine you could accomplish what you are looking for! Feel free to put more detailed comments and if we can direct your implementation.