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

扶醉桌前 提交于 2019-12-19 08:55:16

问题


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?


回答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.




回答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]




回答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



来源:https://stackoverflow.com/questions/17022222/appending-script-src-script-to-head-based-on-screen-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!