Search code examples
javascriptjquerydjangodjango-widget

Defer execution of widget js until page is fully loaded


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.


Solution

  • 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.