Search code examples
ruby-on-railsexceloffice-jsoffice-addinsexcel-addins

Excel Add In - Javascript only working after reload


I am developing an Excel Add-In using the Office-JS Library. When some pages are loaded, the JS is not loaded properly.

The Javascript only works after reloading the page.

I disabled turbolink as suggested in another question. But my problem still appears.

My office_connect.js contains the following:

//= require jquery3
//= require jquery_ujs
//= require_self
//= require select2-full
//= require select2_locale_de

And the head of my layout file:

<%= yield :head_top %>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

<%= stylesheet_link_tag "office_connect"%>
<%= javascript_include_tag "office_connect_app"%>
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
<%= javascript_include_tag "oc_function"%>
<%= javascript_include_tag "office_excel"%>

<title><%=t('layouts.head.text_immodatacockpit')%></title>
<%= csrf_meta_tag %>

<%= yield :head %>

The oc_function file starts Office JS:

// The initialize function must be run each time a new page is loaded.
(function () {
    Office.initialize = function (reason) {
        // If you need to initialize something you can do so here.
    };
})();

A shortened version of my excel.js:

(function () {
    "use strict";

    var cellToHighlight;
    var messageBanner;
    var config;
    var sheetData;
    let housing_output_template_new;
    let housing_output_template_edit;

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {
            
            $(".spinner").hide();
            // If not using Excel 2016, use fallback logic.
            if (!Office.context.requirements.isSetSupported('ExcelApi', '1.1')) {
              $('#subtitle').text("Opps!");
              $("#template-description").text("Sorry, this sample requires Word 2016 or later. The button will not open a dialog.");
              $('#button-text').text("Button");
              $('#button-desc').text("Button that opens dialog only on Word 2016 or later.");
                return;
            }
            $("#select1").select2({placeholder: 'Please choose' , language:'<%= I18n.locale %>',dropdownAutoWidth:true});
            $(".select4").select2({placeholder: 'Please choose' , language:'<%= I18n.locale %>',dropdownAutoWidth:true});
            });
    }
})();

I think it has something to do with the order I load the JS libraries.

Could you point me in the direction of what I am missing?


Solution

  • It looks like you are assigning Office.initialize in two places. If these calls are on two different pages, then that's OK. But you shouldn't be doing this twice on the same page.