If I have two different JavaScript files in the HTML document. Is it possible to toggle between them according to the screen size?
This means script1 is turned off in desktop, script2 is on. On the smartphone, at for example 850px, script2 turns on and script1 off.
script src="script1"></script
script src="script2"></script
Is there any possibility?
I thought about giving the script a class and use
@media only screen and (max-width: 850px)
, but I did not come much further.
CodePudding user response:
Check out here first to have a better understanding:
What you should do is check the value of the screen's width and then based on that load the corresponding javascript file.
<script>
if (screen.width > 500) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'helper.js';
head.appendChild(script);
}
</script>
CodePudding user response:
Create a js(link that to html as a main) file which only checks for screen width and load different script according to viewport.
You can either use window.matchMedia or screen.width