简体   繁体   中英

Javascript write new javascript links based on screen size

I'm trying to figure out how to write the following, ONLY if window width size is 480 or less.

<%= javascript_include_tag 'idangerous.js' %>
<%= javascript_include_tag 'custom.js' %>
<%= stylesheet_link_tag 'idangerous.swiper' %>

So far what I have is the following:

<script type="text/javascript">
$(function () {
  var width = $(window).width();
  if (width <= 480) {
    _output.innerHTML = "<%= javascript_include_tag 'idangerous.js' %>";
    _output.innerHTML = "<%= javascript_include_tag 'custom.js' %>";
    _output.innerHTML = "<%= stylesheet_link_tag 'idangerous.swiper' %>";
  }
});
</script>

However that doesn't work and I don't want to use document.write . I also tried to append in header, but I want this written in the bottom of my page, before </body>

Any other simplified solutions that work?

As you can't append script tags as strings (at least not without splitting the string) since the browser HTML parser will see the </script> within the string and it will interpret it as the end of the script element, you'll have to create them dynamically

if (window.clientWidth <= 480) {
    var scripts = ['idangerous.js', 'custom.js', 'idangerous.swiper'];
    for (var i=0; i<scripts.length; i++) {
        addScript(scripts[i])
    }
}

function addScript(src) {
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = src;
   head.appendChild(script);
}

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