Question

I have this jQuery to detect the screen size and then append a file to the header based on the sceen size.

var scriptSrc = '';
var widowWidth = $(window).width();
if(widowWidth >= 1024)
  scriptSrc = '/js/desktop.js';
if((widowWidth <= 1023) && (widowWidth >= 768))
  scriptSrc = '/js/tablet.js';
else if(widowWidth <= 767)
scriptSrc = '/js/mobile.js';
var script = document.createElement('script');
script.src = scriptSrc;
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);

I have tried to use $(window).resize() with it but I have been unable to remove the file that was originally added before the resize is triggered.

I have a JSFIDDLE for you to change my code on and as you can see it will add the js file based on the screen size but I would like it to change if the screen does too.

Thanks for your time!

Was it helpful?

Solution

Here is what I use:

$(window).bind('resize', function(event) {      
//Whatever you want to run here     

});

Just set a variable for you window width and height and check what they are at inside of this function.

As for changing your javascript file when the screen is resized with out reloading the whole page... I don't think that is possible. A work around might be to import all the javascript files into one file and just run different functions that overwrite any changes that the last javascript function made.

This obviously uses jQuery though.

OTHER TIPS

Add your code into the callback function for the resize event.

$(window).resize(function(elem){
    var scriptSrc = '';
    var widowWidth = $(window).width();
    if(widowWidth >= 1024)
      scriptSrc = '/js/desktop.js';
    if((widowWidth <= 1023) && (widowWidth >= 768))
      scriptSrc = '/js/tablet.js';
    else if(widowWidth <= 767)
      scriptSrc = '/js/mobile.js';
    var script = document.createElement('script');
    script.src = scriptSrc;
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(script);
});

The callback function will be called when the window is resized. However, the event will be fired for every pixel that the window changes in size, so be prepared for that

If I understand your question correctly you want to listen to the window resize event

var onsize = function() {
    var W = $(window).width();
    if(W >= 500) {
      test.html('/js/desktop.js');
    } else if(W >= 300) {
      test.html('/js/tablet.js');
    } else { //if(widowWidth <= 767)
      test.html('/js/mobile.js');
    }
};

I added a div to display the output.

$(window).resize(onsize);

Here's the fiddle http://jsfiddle.net/devm33/aC8Ez/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top