appending [removed][removed] to head based on scre

2019-02-18 01:43发布

问题:

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