файл index.html содержит строки <script src="./assets/s.js"></script> <script…
- User
файл index.html содержит строки
Файл s.js содержит строки
let messages = []; let currentChatTitle = ''; let chatIds = []; let currentChatId = null; let editchatid; let deletechatid; let ansstat = 0;
let userId = localStorage.getItem('userId'); if (!userId) { userId = generateUUID(); localStorage.setItem('userId', userId); } console.log('UUID: ', userId);
let ws;
// Начальное подключение connect();
document.addEventListener('DOMContentLoaded', function() { // Удаляем хеш из URL при загрузке страницы (закрытие форм редактирования и удаления при перезагрузке страницы) window.history.replaceState({}, document.title, window.location.pathname);
// Инициализируем чаты после загрузки DOM initializeChatHistory(); // Скрипт для установки текущего года document.getElementById('current-year').textContent = new Date().getFullYear(); });
// Инициализация чата. function initializeChatHistory() {
//Устанавливаем активную модель setActiveModel(); // Получаем все Id из localStorage, чтобы синхронизировать chatIds chatIds = []; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (key.startsWith('chatHistory_')) { // Извлекаем числовое значение ID из ключа 'chatHistory_key' const id = parseInt(key.split('_')[1], 10); if (!isNaN(id)) { chatIds.push(id); } } } // Сортируем массив chatIds по возрастанию chatIds.sort((a, b) => a - b); // Обновляем chatHistoryIds в local storage if (chatIds.length > 0) { saveChatHistoryIds(chatIds); //console.log('111'); } else { console.log('Архив с ID бесед не найден или он пуст.'); } const savedActiveChatId = localStorage.getItem('activeChatTab'); // Если есть хотя бы один ID чата if (chatIds.length > 0) { //currentChatId = chatIds[0]; // Устанавливаем текущий ID из активного таба, если он существует, иначе делаем активным первый чат в списке currentChatId = savedActiveChatId && chatIds.includes(parseInt(savedActiveChatId, 10)) ? parseInt(savedActiveChatId, 10) : chatIds[0]; const loadedChat = loadChatHistory(); // Устанавливаем текущую беседу messages = loadedChat; const stored = localStorage.getItem(`chatHistory_${currentChatId}`); // Получаем название чата if (stored) { const dialogData = JSON.parse(stored); currentChatTitle = dialogData.title; } else { currentChatTitle = 'Чат'; } console.log(`Загруженная история для диалога с ID ${currentChatId} обработана. Количество сообщений: ${loadedChat.length}.`); // Проверяем и отображаем сообщения, если они есть if (messages.length > 0) { showmessages(messages); MathJax.typesetPromise(); } else { console.log('Чат пуст, отображать нечего.'); } // Прокрутка страницы до конца const block = document.getElementById("parent"); block.scrollTop = block.scrollHeight; document.getElementById("prompt").focus(); } else { console.log('Нет сохраненных чатов для отображения. Создал новую беседу.'); // Создаем новую пустую беседу currentChatId = 1; // Устанавливаем текущую беседу пустой messages = []; currentChatTitle = 'Новая беседа'; // Сохраняем пустую беседу saveChatHistory(messages); //console.log(chatIds); } createTabsForAllChats();}
Но в консоли после обновления страницы index.html ошибка
s.js:1018 Uncaught ReferenceError: MathJax is not defined at initializeChatHistory (s.js:1018:4) at HTMLDocument. (s.js:26:1)
- Assistant
Ошибка
Uncaught ReferenceError: MathJax is not definedвозникает, потому что скрипт MathJax загружается асинхронно, и в момент вызоваMathJax.typesetPromise()объектMathJaxеще не был инициализирован.Чтобы исправить эту проблему, вы можете использовать следующий подход:
-
Добавьте обработчик события для загрузки скрипта MathJax, чтобы дождаться его полной загрузки и инициализации перед вызовом
MathJax.typesetPromise(). -
Переместите вызов
MathJax.typesetPromise()внутрь коллбэка, который будет выполнен после загрузки и инициализации MathJax.
Вот как это можно сделать:
document.addEventListener('DOMContentLoaded', function() { // Удаляем хеш из URL при загрузке страницы window.history.replaceState({}, document.title, window.location.pathname); // Инициализируем чаты после загрузки DOM initializeChatHistory(); // Скрипт для установки текущего года document.getElementById('current-year').textContent = new Date().getFullYear(); // Ждем загрузки MathJax перед вызовом typesetPromise if (typeof MathJax !== 'undefined') { MathJax.typesetPromise().catch((err) => console.error('MathJax error:', err)); } else { const script = document.createElement('script'); script.src = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"; script.async = true; script.onload = () => { MathJax.typesetPromise().catch((err) => console.error('MathJax error:', err)); }; document.head.appendChild(script); } });Теперь мы проверяем, доступен ли
MathJaxпосле загрузки DOM. Если он доступен, мы вызываемtypesetPromise(), если нет — создаем новый элемент<script>, который загружает MathJax и затем вызываетtypesetPromise()в обработчикеonload.Проверьте также, что вы не вызываете
MathJax.typesetPromise()до завершения инициализации MathJax в другом месте вашего кода. -
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.