How to ensure my javascript function only executes after all external javascripts are loaded?

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

  •  22-04-2021
  •  | 
  •  

Вопрос

I am developing a WebPart in SharePoint,and I need to draw something in my WebPart using excanvas.js.But sometimes it shows nothing.The error message is:

Object doesn't support property or method 'getContext'

When I debug it,it breaks at here:

var ctxBg = document.getElementById(backgroundId).getContext("2d");

The "backgroundId" is the id of one canvas element. This error happens not every times,just sometimes,so I think if my js function is executed before the excanvas.js is loaded.I register the excanvas.js with the code:

this.Page.ClientScript.RegisterClientScriptInclude("ExCanvasJs", "wpresources/MyWebPart/js/excanvas.js");

So how to ensure my function is executed after the excanvas.js is loaded?Or I'm wrong at this problem?Would you give me your advice?

my js function:

function DrawMeter(meter, contextCollection) {
var backgroundId = meter.meterbackground;
var pointerId = meter.meterpointer;
var containerId = meter.metercontainer;
if (contextCollection != null && contextCollection.length > 0) {
    for (var i = 0; i < contextCollection.length; i++) {                    
        DrawSingleMeter(backgroundId + "_" + i, pointerId + "_" + i, containerId + "_" + i, contextCollection[i]);
    }
}

function DrawSingleMeter(backgroundId, pointerId, containerId, context) {
var ctxBg = document.getElementById(backgroundId).getContext("2d");
var ctxPointer = document.getElementById(pointerId).getContext("2d");
drawing...

}

Это было полезно?

Решение

you need to put it into a page ready handler. otherwise at the time the javascript is executed the element might not be available yet.
consider using jquery or another js library for this, if you can't use it here's a link on how to use the native js version of the onload event

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top