【问题标题】:Why dynamically added JS and CSS doesn't work?为什么动态添加的 JS 和 CSS 不起作用?
【发布时间】:2021-11-17 11:37:04
【问题描述】:

加载了一个包含脚本和样式的数组,将 JS 和 CSS 添加到 head 但不起作用。见screen here

代码

$.ajax({
  url:'https://gorodok.net.ua/api/NFTBot/php/get_payload.php',
  type:'get',
  dataType: 'json',
  success: function(data){
    console.log(data);
  data.forEach(function(src) {
  console.log(src)
  var  unknown;
  if (src.includes('.js')) {
     unknown = document.createElement('script');
     unknown.src = src;
     unknown.async = false;
     unknown.type = 'text/javascript';
   } else if (src.includes('.css')) {
    unknown = document.createElement('link');
    unknown.href = src;  
    unknown.async = false;
    unknown.type = 'text/css';
    unknown.rel = 'stylesheet';
  }
  document.head.appendChild(unknown);
  //document.body.appendChild(unknown);
});},
  error: function(error){console.log("EROR:" + error)}
});  

如果通过“显式”数组添加相同的脚本和样式,一切正常。

工作代码

["https://gorodok.net.ua/api/NFTBot/NFTBot.js","https://gorodok.net.ua/api/NFTBot/style/main.css"].forEach(function(src) {
  var  unknown;
  if (src.includes('.js')) {
     unknown = document.createElement('script');
     unknown.src = src;
     unknown.async = false;
     unknown.type = 'text/javascript';
   } else if (src.includes('.css')) {
    unknown = document.createElement('link');
    unknown.href = src;  
    unknown.async = false;
    unknown.type = 'text/css';
    unknown.rel = 'stylesheet';
  }
  document.head.appendChild(unknown);
});

【问题讨论】:

  • 它不能按预期工作的原因可能有很多。请求会产生错误吗?在这种情况下会调用success 函数吗?你能处理error 函数中的错误吗?如果没有错误并且调用了函数,您是否收到了有效的 json 字符串(因为您接受了 json dataType)?那个json是怎么格式化的?你能发布一个实际的例子吗?
  • 好的,我正在编辑我的问题。和新屏幕:ibb.co/RCCj5rM
  • 第一个例子中有什么理由是 document.body.appendChild(unknown);并在第二个 document.head.appendChild(unknown);?
  • 刚刚尝试了不同的选项,但bodyhead 不起作用

标签: javascript jquery ajax dom


【解决方案1】:

答案:async:false - 将设置添加到 ajax

代码:

$.ajax({
  async: false,
  url:'https://...',
  type:'get',
  dataType: 'json',
  success: function(data){

....

.

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2014-12-14
    相关资源
    最近更新 更多