How to detect window resize and then change the javascript file being added to the header?

StackOverflow https://stackoverflow.com/questions/23349915

문제

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!

도움이 되었습니까?

해결책

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.

다른 팁

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/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top