appending <script src=""></script> to head based on screen width
Solution 1
See it in action: Short Demo
You can define a function, like this:
function appendScript(pathToScript) {
var head = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.src = pathToScript;
head.appendChild(js);
}
And then call it with the appropriate argument (e.g. according to screen size), like this:
appendScript("path/to/file.js");
If you also need to remove a script from head
(e.g. based on its 'src' attribute), you can define a function, like this:
function removeScript(pathToScript) {
var head = document.getElementsByTagName("head")[0];
var scripts = head.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var js = scripts[i];
if (js.src == pathToScript) {
head.removeChild(js);
break;
}
}
}
And then call it with the appropriate argument (e.g. according to screen size), like this:
removeScript("path/to/file.js");
Also, note that using screen.width
returns the size of the user's screen (not the browser-window's width).
If you need to get the window size you can use $(window).width()
(using jQuery).
If you want a "jQuery-free" solution, take a look at this answer for cross-browser alternatives.
Solution 2
You can create a script element and set its src property then append it to the head of the document
var script = document.createElement('script');
script.src = 'js.js';
document.head.appendChild(script)
if wants to support IE < 9 then instead of document.head
use document.getElementsByTagName('head')[0]
Solution 3
Using yepnope
you can do something like
yepnope([{
test: 768 >= screen.width // devices 768 and up
, yep: [ "site/js/jquery.stickyPanel.min.js" ]
, complete: function () { alert('complete'); }
}]);
And it will append the file automatically
valerio0999
Updated on June 04, 2022Comments
-
valerio0999 almost 2 years
i need something easy like this:
<script type="text/javascript"> <!-- if (screen.width <= 699) { document.location = "mobile.html"; } //--> </script>
but instead of a redirect i'd need
<script src="js.js"></script>
to be appended in<head></head>
is that possible?
-
Ben Hull almost 11 yearsYepnope.js is great, and available standalone, if all you need is to choose between files.
-
valerio0999 almost 11 yearscan i have some help? i'd love to make the yepnope script work. here's my code, but it's not appending anything. what am i doing wrong? thank you! <script src="site/js/yepnope.js"></script> <script> yepnope([{ test: 768 >= screen.width , yep: [ "site/js/jquery.stickyPanel.min.js" ] }]); </script>
-
valerio0999 almost 11 yearsthanks for you help ahmad but the script seems to work only with "<" ... no ">" or ">=" and anyway, i get <object width="0" height="0" data="site/js/jquery.stickyPanel.min.js"></object> appended.. but what i need is <script src="site/js/jquery.stickyPanel.min.js"></script>
-
valerio0999 almost 11 yearsi tried this too.. but it's not working.. here is my script <script> function appendScript(pathToscript) { var head = document.getElementsByTagName("head")[0]; var js = document.createElement("script"); js.type = "text/javascript"; js.src = pathToScript; head.appendChild(js); } if (screen.width >= 768) { appendScript("site/js/jquery.stickyPanel.min.js"); } </script>
-
Ahmad Alfy almost 11 yearsOK remove the alert and replace it with the code that initiate your sticky panel and it will work
-
valerio0999 almost 11 yearsthis appends it correctly, but in any case (even under 768px width). here is my script: <script> if (screen.width >= 768) { var script = document.createElement('script'); script.src = 'site/js/jquery.stickyPanel.min.js'; document.head.appendChild(script) } </script>
-
gkalpak almost 11 years@omegaiori: Maybe it is because you seem to name your argument "pathToscript" (lower-case 's'), but then try to use it as "js.src = pathToScript" (upper-case 's'). (It's a typo in my answer - I'll fix it - sorry for that.) If this does not solve the problem, try to see what is wrong using your developer console.
-
valerio0999 almost 11 yearsactually what initiaziles stickypanel is in another .js - is that mandatory? it's not just that it's not working, it's probably not working because nothing is appended. sorry to bother you so much but if you can help, that would be great :)
-
valerio0999 almost 11 yearsok it's working BUT the "if (screen.width >= 768)" is ignored, the script is appended in any case. the console says nothing ( "CSS Usage: initializing extensions")
-
gkalpak almost 11 yearstry adding
alert(screen.width);
just before yourif
statement. What does it report ? -
valerio0999 almost 11 yearsit says 1366px even if when the browser is stretched at less then 1366 .. well i guess that's why it always appends it. should i change it to window.size or something?
-
valerio0999 almost 11 yearsdo i need an "else" statement? the "else" i'd need would be: 'append nothing' :)
-
gkalpak almost 11 years@omegaiori: No, you don't need an else statement. Using
screen.*
returns the size of the screens (regardless of the size of the browser window). In order to get the browser-window size see this answer. -
Ahmad Alfy almost 11 yearsWhen I try this snippet, it successfully loads the JS file I inject in my document. Can you try adding something like
console.log('file loaded')
in the beginning of your file? -
valerio0999 almost 11 yearsno actually that didn't solve it :\ i would need something that reacts to browser window size too. let me explain in detail what i need: im doing a responsive website, and to save bandwidth, i don't want to load certain javascripts from 768px wide screen and below. i actually found a lot of complicated answers around, but none of them actually really helped :\ sorry for being such a noob
-
gkalpak almost 11 years@omegaiori: Have you read my updated answer ? If you use
$(window).width()
instead ofscreen.width
gives you the browser-window width, which is what you wanted. What is the problem ? -
valerio0999 almost 11 yearsi get: ReferenceError: yepnope is not defined
-
valerio0999 almost 11 yearsgreat, it works! sorry but the script that initialized the js broke my site, i moved it in the bigger js and now it's working fine :) thanks.. here's my final script: <script> function appendScript(pathToScript) { var head = document.getElementsByTagName("head")[0]; var js = document.createElement("script"); js.type = "text/javascript"; js.src = pathToScript; head.appendChild(js); } if ($(window).width() >= 768) { appendScript("site/js/jquery.flexslider.js"); } </script>
-
valerio0999 almost 11 yearsthankssss it's working in my real case also :) one last question: how would the script be if i wanted to REMOVE a script, let's say <= 768 ?
-
gkalpak almost 11 years@omegaiori: I updated my answer. Read the section about removing a script and also take a look at the short demo I provided to watch it in action.
-
light24bulbs about 6 yearsDoes this block your script until the browser loads the script? what happens timing wise?
-
gkalpak about 6 yearsWell...it's complicated :D html5rocks.com/en/tutorials/speed/script-loading