3

While loading a JS SDK on our website I was trying out few different ways. I noticed that Snippet 1 causes CORS error, while Snippet 2 loads the same script on same page without any issues.

Snippet 1 (Using document.body.appendChild, throws CORS exception)

 const url = 'https://www.example.com/sdk.js';
 const scriptTag = document.createElement('script');
 scriptTag.setAttribute('crossorigin', 'anonymous');
 scriptTag.setAttribute('src', url);
 document.body.appendChild(scriptTag);

Snippet 2 (Using parentNode.insertBefore, no CORS exception)

 const element = document.getElementsByTagName('script')[0];
 const scriptTag = document.createElement('script');

 scriptTag.async = !0;
 scriptTag.crossorigin = 'anonymous';
 scriptTag.src = 'https://www.example.com/sdk.js';
 element.parentNode.insertBefore(scriptTag, element);

I tried to find why the behaviour is different for each case, but could not find any reason for it.

Can someone point out to me why I see this behaviour?

2
  • 2
    I think the element property name is "crossOrigin", not "crossorigin". Commented Mar 5, 2020 at 20:14
  • You are right, just tested with scriptTag.crossOrigin = 'anonymous' and now I get the same behaviour. Thanks! 🙏 Commented Mar 6, 2020 at 6:58

1 Answer 1

1

The only difference I see running your code is the on pointed by @Pointy on the comment, the first script generates:

<script crossorigin="anonymous" src="https://www.example.com/sdk.js"></script>

the second one:

<script async="" src="https://www.example.com/sdk.js"></script>

running on my console, so probably the crossorigin is responsable for the cors error. (the same happened on console, btw)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.