简体   繁体   中英

appending <script src=“”></script> to head based on screen width

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?

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 (eg according to screen size), like this:

appendScript("path/to/file.js");

If you also need to remove a script from head (eg 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 (eg 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.

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM