user736893
user736893

Reputation:

Reprocess code for a dynamically loaded "widget"?

I have the following code that loads a tile, or "widget", in my UI. Occasionally (like on orientation change) I have to redraw the tiles. Some of the content is generated by a script load event. During the redraw, this event is not getting loaded again. How can I accomplish this?

//html
let $elTile = $('<div/>').appendTo($elContainer);
$elTile.load('tiles/' + tile.name + '/' + tile.name + '.html #' + tile.name + '-content');
//javascript
$.getScript('tiles/' + tile.name + '/' + tile.name + '.js');
//css
$('head').append( $('<link rel="stylesheet" type="text/css" />')
    .attr('href', 'tiles/' + tile.name + '/' + tile.name + '.css'));

And here is what one of the tile script files looks like:

window.addEventListener("load", function() {
    //do some stuff that may need to be called again on orientation change
});

I see from questions like this and this that I probably can't just "unload and reload" the script, so is there another way to process the "tile initialization" script again?

Orientation Change was just an example, I'd like to be able to call the tile init script arbitrarily if possible.

Upvotes: 1

Views: 155

Answers (2)

lscmaro
lscmaro

Reputation: 1065

Depending on your device support and requirements, you could do a few things.

One would be to deal with this by also adding orientationchange to your event listener.

$(window).on('load orientationchange', function(){ /* run your code for both*/});

Another option would be to use the resize event.

The former would be device specific as all browsers act differently, as mentioned in this post.

UPDATE: You can also create an anonymous event based function that you can call at will using your event as the trigger. For example.

$(window).on('myCustomEvent', function(){ /*whatever code you want to run at any time*/});

Then you can trigger such event from any logic point you need:

if ($(window).width() < 1024){
   $(window).trigger('myCustomEvent');
}

Upvotes: 1

rafaelcastrocouto
rafaelcastrocouto

Reputation: 12161

You can use other events, like "orientationchange" https://developer.mozilla.org/en-US/docs/Web/Events/orientationchange

Or you can recall the load function like this:

var myFunction = function () {
  //do some stuff that may need to be called again on orientation change
};
window.addEventListener("load", myFunction);
window.addEventListener("orientationchange", myFunction);
...

And you can call it again anytime just using myFunction();

Upvotes: 0

Related Questions