I’m having trouble with the Twitch Player on my webpage. When I try to run this code, I get an error saying Uncaught ReferenceError: Twitch is not defined:
<div id="streamContainer">
<script src="https://player.twitch.tv/js/embed/v1.js"></script>
<div id="streamPlayer"></div>
<script>
var playerConfig = {width:800,height:600,channel:"gamingLive"};
var twitchPlayer = new Twitch.Player("streamPlayer", playerConfig);
twitchPlayer.setVolume(0.7);
</script>
</div>
It works fine in jsfiddle but not on my actual page. The rest of the page loads okay, just not this part. I can see the Twitch embed JS file in my browser’s sources tab. I’ve tried this in both Chrome and Firefox with the same result. Any ideas on what might be causing this or how I can troubleshoot it? Is there a way to check if the Twitch object is loaded properly?
This issue often stems from script loading order. Ensure the Twitch embed script is fully loaded before initializing the player. Try moving your script to the end of the body tag or use a DOMContentLoaded event listener:
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = 'https://player.twitch.tv/js/embed/v1.js';
script.onload = function() {
var playerConfig = {width:800, height:600, channel:'gamingLive'};
var twitchPlayer = new Twitch.Player('streamPlayer', playerConfig);
twitchPlayer.setVolume(0.7);
};
document.body.appendChild(script);
});
This approach dynamically loads the Twitch script and initializes the player once it’s ready. It should resolve the ‘Twitch’ object undefined error. If problems persist, check for any conflicting scripts or CSP restrictions on your page.
I’ve encountered this issue before, and it’s often related to timing. The Twitch embed script might not be fully loaded when your code tries to use it.
Try wrapping your player initialization code in a function and calling it after the Twitch API is ready. You can do this by adding an event listener for when the script loads:
<div id=\"streamContainer\">
<script src=\"https://player.twitch.tv/js/embed/v1.js\"></script>
<div id=\"streamPlayer\"></div>
<script>
function initTwitchPlayer() {
var playerConfig = {width:800,height:600,channel:\"gamingLive\"};
var twitchPlayer = new Twitch.Player(\"streamPlayer\", playerConfig);
twitchPlayer.setVolume(0.7);
}
if (window.Twitch && window.Twitch.Player) {
initTwitchPlayer();
} else {
window.addEventListener('twitchPlayerAPIReady', initTwitchPlayer);
}
</script>
</div>
This approach ensures the Twitch API is loaded before trying to use it. If that doesn’t work, check your browser’s console for any other errors that might be interfering with script execution.