0

I want to add script after all scripts loaded. My code is:

var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var get = document.getElementsByTagName("script");
var count = get.length;

var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[count];
s1.async=true;
s1.src='https://embed.tawk.to/57c6c47b2b03647ba16e0e84/default';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();

And I got this error:

Uncaught TypeError: Cannot read property 'parentNode' of undefined

The link is: https://www.alapar.az/

6
  • 1
    Can you edit your post to include an actual question?
    – Brennan
    Aug 31, 2016 at 19:58
  • Does document contain <script> elements before function is called? Aug 31, 2016 at 20:11
  • of course! check this link: alapar.az Aug 31, 2016 at 20:13
  • Your s0 variable isn't being assigned correctly before you're looking for its parent node. You may want to try wrapping this in another init() function and adding a script tag as the last element in your dom that calls init(); that way theoretically all your other script tags will be in place before you try to get the length of them. I can't check your code but I bet if you console.log(count) right after your var count = get.length your count will return as 0 or undefined. Aug 31, 2016 at 20:22
  • can someone put here code? I couldn't understand. I have poor english Aug 31, 2016 at 20:29

1 Answer 1

0

Substitute

s0=document.getElementsByTagName("script")[count -1] // note `-1`

for

s0=document.getElementsByTagName("script")[count]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.