摘自杰瑞 · 赫尔曼的《你好,多莉》歌曲: 江湖可能因为少了谁而失色,却不会因为少了谁后就不再是江湖。 —高手寂寞-

js加载问题

内容目录

1.js加载速度不同,导致使用两者参数出错。

问题:两个js文件加载速度不同,导致一个js文件中的js的配置信息未配置,另一个文件中要使用这个信息为undefine。(这个文件是要在外部公用这些信息,其中配置使用全局配置window.属性)。

解决方式:

  1. 使用监听器,在a文件配置后,添加一个监听器,然后在b文件使用时调用这个监听器。

    示例:

    //文件a
    const loadChatWidget = (chatId) => {
     const script = document.createElement('script');
     script.src = 'http://localhost:3000/chatbot.js'; // Replace with the actual chatbot.js URL
     // script.async = true;
     script.onload = () => {
       window.chatbotConfig = {
         token: 'BBPVIV6RPN6LNQJ4W362', // Replace with the actual token
         datasourceId: 'ds_60RgBBYSJmjtJ13XKXhQ1t', // Replace with the actual datasource ID
         chatId: chatId,
         themeColor: 'blue', // Default theme color
         chatWindowName: 'AskTable 对话机器人',
         defaultOpen: true // Ensure chat window is open by default in this context
       };
       if (window.initializeChatWindow) {
         window.initializeChatWindow();
       }
    
       // Dispatch a custom event to signal that chatbotConfig is ready
       // 添加监听器
       const event = new CustomEvent('chatbotConfigReady', { detail: window.chatbotConfig });
       window.dispatchEvent(event);
     };
     document.body.appendChild(script);
    };
    
    // 调用 loadChatWidget 并传递 chatId
    loadChatWidget('someChatId'); // Replace 'someChatId' with the actual chatId
    //文件b
    let config = {
     ...defaultConfig,
     ...window.chatbotConfig
    };
    
    // 定义一个函数来更新配置
    const updateConfig = (newConfig) => {
     config = {
       ...defaultConfig,
       ...newConfig
     };
     console.log(621, config); // 打印更新后的配置
    };
    
    // 监听事件并更新配置
    window.addEventListener('chatbotConfigReady', (event) => {
     updateConfig(event.detail); // 使用事件的详细信息更新配置
     console.log(333, config); // 在事件触发后打印更新后的配置
    });
    
    // 确保 loadChatWidget 被调用,以便触发事件
    // 可以在需要的地方调用 loadChatWidget 或者确保它已经被调用
    

    局限性:

    • 只能在监听器内部才能使用配置完毕的信息。
    • 导致第二个问题,外部使用时还是之前。方式(外部定义let变量,然后内部修改,再外部查看,结果还是外部的值)

    方式2:目前使用方式:

    • window.属性为全局配置,由于js文件的加载速度不同导致的访问得不同的数据。
    • 思考是否配置文件需要在这块位置执行,放在这个函数外面是否有影响,若无影响则可以放置在外面,这样二者加载时,可以同时访问。

    原因:由于是在script.onload函数里面,这个回调函数是对应的script文件加载完毕后才执行这个回调函数。所以执行之前b文件访问过后 才得到的结果为undefine。

发表评论