0

I have a widget with some custom js:

class ImagePreviewWidget(ClearableFileInput):

    ...

    class Media:

        css = {
            'all': ('css/image-preview-widget.css',)
        }
        js = ('js/image-preview-widget.js', )

The custom js uses jQuery, which is loaded independently, so I need to wrap my module initialization in:

window.onload = function() {
    cusomJsStart();
};

Which is not very clean (one problem is that I am maybe interfering with other window.onload calls). Is there a better way to load the widget javascript?

EDIT

Just to make it clear: the whole point of this question is that jQuery is not yet loaded when the script runs, and that the script loading order is outside my control.

blueFast
  • 41,341
  • 63
  • 198
  • 344

2 Answers2

3

Instead of setting window.onload you should use addEventListener:

window.addEventListener("load", customJsStart);

(If you need to support IE<9 then some fallback code is required - see the MDN link above).

Even nicer would be if you could tell Django to add a defer attribute to the scripts you pass in the Media class, but it doesn't support that yet.

solarissmoke
  • 30,039
  • 14
  • 71
  • 73
0

There is nothing better than pure Javascript ! Alternatively you can use JQuery like this :

$(function(){
   cusomJsStart();
});

But with this method your page will be heavier because of JQuery source file loading.

Or you can put your cusomJsStart() at the end of your HTML file, but it's not clean at all ! You did the right choice.

Raphaël Vigée
  • 2,048
  • 14
  • 27
  • Second time I mention this (the other answer has been deleted), which I thought was obvious from the question: the whole point of the question is that **jQuery is not yet loaded** when the script runs, and that the script loading order is outside my control. I'll add this to the question. – blueFast Nov 01 '15 at 05:31