Adding Javascript to a sandboxed Visual Web Part

Adding JavaScript to a sandboxed Visual Web Part seems to work best when using the following script inside the .ascx file:

<script type="text/javascript">
    SP.SOD.executeFunc("~sitecollection/_catalogs/siteassets/MyWebPart/MyWebPartScript.js", null, LoadMyScript);
    //the following two variables keep the page with the web part from freezing and becoming uneditable when in edit mode
    var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
    var wikiInEditMode = document.forms[MSOWebPartPageFormName]._wikiPageMode.value;
    if (inDesignMode !== 1 & wikiInEditMode !== 1) {
        function LoadMyScript() {
            if (typeof MyNameSpace != "undefined") {
                MyNameSpace.MyWebPart.start();
            } else {
               //add code for presenting error message to end user here
            }
        }
    }
</script>

Leave a Reply