BuilderIO / partytown

Relocate resource intensive third-party scripts off of the main thread and into a web worker. 🎉
https://partytown.builder.io
MIT License
12.88k stars 427 forks source link

Problem with the JSONP callback #96

Open jakubsobel opened 2 years ago

jakubsobel commented 2 years ago

I'm trying to use Partytown with a GTM script in our project. The problem is, inside of the GTM we have a custom snippet that is using JSONP to get the data. Just a regular:

<script>
    function jsonpCallback(data) {
        // some code here
    }
</script>
<script src="https://some-url?callback=jsonpCallback"></script>

After the Partytown is enabled this will no longer work. It looks like the jsonpCallback from the first script tag is not accessible in the the second script tag.

Minimal reproduction: https://github.com/jakubsobel/partytown-jsonp-issue Just run it, go to the localhost:3000 and you will see that the log is missing. That's because the response is:

typeof jsonpCallback === 'function' && jsonpCallback([/*endpoint data*/]);

and for some reason while using Partytown the previously defined jsonpCallback is not defined.

Remove the type="text/partytown" from both of the script tags and the jsonpCallback will execute showing the log.

jakubsobel commented 2 years ago

Solution provided in https://github.com/BuilderIO/partytown/issues/114#issuecomment-1068907119 works. Adding jsonpCallback to the globalFns array in the partytown config fixes the issue e.g.:

<script>
  partytown = {
    globalFns: ["jsonpCallback"],
  };
</script>