I
I
IliaMal2021-07-09 12:30:52
AJAX
IliaMal, 2021-07-09 12:30:52

Why doesn't js work in the template loaded via fetch()?

Hello.

In the product card, when changing the characteristics of the product, I reload the catalog.element with the necessary parameters via ajax (more precisely, via the js fetch() method).

The content is loaded correctly, but the scripts are not executed. Moreover, the problem is not in the absence of elements in the DOM, but in something else. Even console.log(); written in template.php is not executed.

Disabled catalog.element caching.

Maybe you need to add something to fetch () so that the loaded scripts are executed?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Shamanov, 2021-07-09
@SilenceOfWinter

you hang event handlers on specific elements and when the content is reloaded, they will be deleted along with the dom elements to which they are attached. xs how this is done in native js, in jquery it is solved like this:

$('#ajax-container').on('click', '.inner-element', function (event) {...});

ajax-container - the container in which the content is loaded.
inner-element - the element to load

N
Nadim Zakirov, 2021-07-09
@zkrvndm

Something to add) Not everything is so simple. There are no handlers in the loaded html code, this is the problem. You need to reinstall all the handlers necessary for the scripts to work again.

A
Alexandroppolus, 2021-07-09
@Alexandroppolus

If I understand correctly, fetch returns some html, which is then stuck into someElement.innerHTML? Then all the <script> tags in this html will simply be added, but will not work. You need to find them as someElement.querySelectorAll('script') and "re-add" each one manually, then the code in them will work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question