4

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?

valerio0999
  • 9,029
  • 6
  • 24
  • 52

3 Answers3

16

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.

Community
  • 1
  • 1
gkalpak
  • 46,029
  • 8
  • 97
  • 116
  • i tried this too.. but it's not working.. here is my script – valerio0999 Jun 10 '13 at 13:20
  • @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. – gkalpak Jun 10 '13 at 13:36
  • ok 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") – valerio0999 Jun 10 '13 at 13:53
  • try adding `alert(screen.width);` just before your `if` statement. What does it report ? – gkalpak Jun 10 '13 at 14:01
  • it 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 Jun 10 '13 at 14:07
  • do i need an "else" statement? the "else" i'd need would be: 'append nothing' :) – valerio0999 Jun 10 '13 at 14:12
  • @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](http://stackoverflow.com/questions/3437786/how-to-get-web-page-size-browser-window-size-screen-size-in-a-cross-browser-wa)**. – gkalpak Jun 10 '13 at 14:20
  • no 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 – valerio0999 Jun 11 '13 at 08:05
  • @omegaiori: Have you read my updated answer ? If you use `$(window).width()` instead of `screen.width` gives you the browser-window width, which is what you wanted. What is the problem ? – gkalpak Jun 11 '13 at 08:17
  • great, 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: – valerio0999 Jun 11 '13 at 09:17
  • thankssss 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 ? – valerio0999 Jun 11 '13 at 09:46
  • @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. – gkalpak Jun 11 '13 at 10:46
  • Does this block your script until the browser loads the script? what happens timing wise? – light24bulbs Apr 05 '18 at 17:30
  • Well...it's complicated :D https://www.html5rocks.com/en/tutorials/speed/script-loading/ – gkalpak Apr 07 '18 at 12:33
5

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]

Community
  • 1
  • 1
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
  • this appends it correctly, but in any case (even under 768px width). here is my script: – valerio0999 Jun 10 '13 at 13:31
1

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

Ahmad Alfy
  • 11,903
  • 6
  • 59
  • 94
  • Yepnope.js is great, and available standalone, if all you need is to choose between files. – Ben Hull Jun 10 '13 at 11:13
  • can 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! – valerio0999 Jun 10 '13 at 12:44
  • thanks for you help ahmad but the script seems to work only with "" or ">=" and anyway, i get appended.. but what i need is – valerio0999 Jun 10 '13 at 13:13
  • OK remove the alert and replace it with the code that initiate your sticky panel and it will work – Ahmad Alfy Jun 10 '13 at 13:29
  • actually 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 Jun 10 '13 at 13:38
  • When 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? – Ahmad Alfy Jun 10 '13 at 22:28
  • i get: ReferenceError: yepnope is not defined – valerio0999 Jun 11 '13 at 08:52