add javascript files to wordpress footer according to page width

I’m trying to add js files to WordPress footer id page width is larger than

<?php if(is_home()){ ?>
<script type="text/javascript">
$(document).ready(function(){
var wid = $(window).width();
if(wid>970){
<?=
'<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/script.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/slider.js"></script>'
?>  
}
});
</script>
<?php } ?>

I’ve tried using .append() but sure I’m facing the same problem and it doesn’t add the files because the script code contains double quotes and single quotes while it’s wrapped in a single quote

Related posts

Leave a Reply

2 comments

  1. You’ll need to add the code to inject tag into the HTML, do it by this:

    <?php if(is_home()){ ?>
    <script type="text/javascript">
    
    $(document).ready(function(){
        var wid = $(window).width(),
            scriptName = wid > 970 ? 'script.js' : 'slider.js',
            url = "<?php bloginfo('template_directory'); ?>/js/" + scriptName,
            script = document.createElement( 'script' );
        script.type = 'text/javascript';
        script.src = url;
        $("body").append( script );
    });
    </script>
    

    It checks page’s width, according to that, select the script’s name then inject is to the end of the body.

  2. What if you try to include the js file in js like this :

    function includeJS() {
      document.write('<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/script.js"></script>
    <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/slider.js"></script>'); 
      }
    
    var wid = $(window).width();
     if(wid>970) {
        includeJS();
      }