@AleDv

Как добавить сторонние библиотеки для JS-виджета?

Есть задача построить встраиваемый на другие сайты js виджет. Для виджета используются библиотеки jquery, highcharts и пара свои скриптов.

Возник вопрос как встроить сторонние библиотеки в виджет? Читал статью и оттуда взял основу по подключению джквери:
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src",
        "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
    if (script_tag.readyState) {
      script_tag.onreadystatechange = function () { // For old versions of IE
          if (this.readyState == 'complete' || this.readyState == 'loaded') {
              scriptLoadHandler();
          }
      };
    } else { // Other browsers
      script_tag.onload = scriptLoadHandler;
    }
    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
}


Но как встроить свои библиотеки - не пойму. Пробовал таким образом:
/******** Load jQuery if not present *********/
    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type","text/javascript");
        script_tag.setAttribute("src",
            "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
        if (script_tag.readyState) {
            script_tag.onreadystatechange = function () { // For old versions of IE
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    scriptLoadHandler();
                }
            };
        } else { // Other browsers
            script_tag.onload = scriptLoadHandler;
        }
        // Try to find the head, otherwise default to the documentElement
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);

        /******** Загрузка highcharts ******/


        var script_tag_highcharts = document.createElement("script");
        script_tag_highcharts.type = "text/javascript";
        script_tag_highcharts.src = "https://code.highcharts.com/highcharts.js";
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag_highcharts);

        var script_tag_highcharts = document.createElement("script");
        script_tag_highcharts.type = "text/javascript";
        script_tag_highcharts.src = "https://code.highcharts.com/modules/exporting.js";
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag_highcharts);

        var script_tag = document.createElement("script");
        script_tag.type = "text/javascript";
        script_tag.src = "http://site.local/js/chart/chartTheme.js";
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);

        var script_tag2 = document.createElement("script");
        script_tag2.type = "text/javascript";
        script_tag2.src = "http://site.local/js/chart/chartOverview.js";
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag2);

    } else {
        // The jQuery version on the window is the one we want to use
        jQuery = window.jQuery;
        main();
    }


Получаю такую ошибку:
52a5bb240eb94a988794932da7cc877b.PNG

Видимо не подключается скрипт https://code.highcharts.com/highcharts.js, т.к. дальше мой скрипт site.local/js/chart/chartOverview.js выполняется.

В js я не силён, скорей всего что-то не учитываю. Подскажите, как правильно встраивать библиотеки?
  • Вопрос задан
  • 188 просмотров
Пригласить эксперта
Ответы на вопрос 1
alexey-m-ukolov
@alexey-m-ukolov Куратор тега JavaScript
Ну так вы проверяете только наличие jQuery на странице и, если его нет, грузите и его и все остальные свои библиотеки. А если jQuery есть, то выполняете свой код.
Видите проблему? Ваш код же зависит не только от jQuery, но и от других библиотек, значит, нужно проверять и их наличие тоже, прежде чем запускать свой виджет.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы