使函数等到元素存在

Ste*_*ven 123 javascript jquery html5 function

我正在尝试在另一个画布上添加画布 - 如何在创建第一个画布之前让这个函数等待启动?

function PaintObject(brush) {

    this.started = false;

    // get handle of the main canvas, as a DOM object, not as a jQuery Object. Context is unfortunately not yet
    // available in jquery canvas wrapper object.
    var mainCanvas = $("#" + brush).get(0);

    // Check if everything is ok
    if (!mainCanvas) {alert("canvas undefined, does not seem to be supported by your browser");}
    if (!mainCanvas.getContext) {alert('Error: canvas.getContext() undefined !');}

    // Get the context for drawing in the canvas
    var mainContext = mainCanvas.getContext('2d');
    if (!mainContext) {alert("could not get the context for the main canvas");}

    this.getMainCanvas = function () {
        return mainCanvas;
    }
    this.getMainContext = function () {
        return mainContext;
    }

    // Prepare a second canvas on top of the previous one, kind of second "layer" that we will use
    // in order to draw elastic objects like a line, a rectangle or an ellipse we adjust using the mouse
    // and that follows mouse movements
    var frontCanvas = document.createElement('canvas');
    frontCanvas.id = 'canvasFront';
    // Add the temporary canvas as a second child of the mainCanvas parent.
    mainCanvas.parentNode.appendChild(frontCanvas);

    if (!frontCanvas) {
        alert("frontCanvas null");
    }
    if (!frontCanvas.getContext) {
        alert('Error: no frontCanvas.getContext!');
    }
    var frontContext = frontCanvas.getContext('2d');
    if (!frontContext) {
        alert("no TempContext null");
    }

    this.getFrontCanvas = function () {
        return frontCanvas;
    }
    this.getFrontContext = function () {
        return frontContext;
    }
Run Code Online (Sandbox Code Playgroud)

Ift*_*tah 236

如果您可以访问创建画布的代码 - 只需在创建画布后调用该函数即可.

如果您无法访问该代码(例如,如果它是第三方代码,例如谷歌地图),那么您可以做的是测试间隔中是否存在:

var checkExist = setInterval(function() {
   if ($('#the-canvas').length) {
      console.log("Exists!");
      clearInterval(checkExist);
   }
}, 100); // check every 100ms
Run Code Online (Sandbox Code Playgroud)

但请注意 - 很多时候第三方代码可以选择在加载完成后激活您的代码(通过回调或事件触发).这可能是你可以放置你的功能的地方.间隔解决方案实际上是一个糟糕的解决方案,只有在没有其他工作时才应该使用.

  • 还有一件事是重要的,当使用给定的解决方案时,你应该在for循环中设置一段代码并设置一个最大重试计数器,如果出现问题,你最终不会得到一个无限循环:) (4认同)
  • 这不是堆栈炸弹,如果该元素从未出现,那么这只是每 100 毫秒调用该函数(在本例中)。这是浪费 CPU 周期,但不会崩溃。 (2认同)

Jam*_*ber 33

这只适用于现代浏览器,但我发现更容易使用,then所以请先测试,但:

function rafAsync() {
    return new Promise(resolve => {
        requestAnimationFrame(resolve); //faster than set time out
    });
}

function checkElement(selector) {
    if (document.querySelector(selector) === null) {
        return rafAsync().then(() => checkElement(selector));
    } else {
        return Promise.resolve(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

或使用生成器功能

async function checkElement(selector) {
    const querySelector = document.querySelector(selector);
    while (querySelector === null) {
        await rafAsync()
    }
    return querySelector;
}  
Run Code Online (Sandbox Code Playgroud)

用法

checkElement('body') //use whichever selector you want
.then((element) => {
     console.info(element);
     //Do whatever you want now the element is there
});
Run Code Online (Sandbox Code Playgroud)


dam*_*amd 31

根据您需要支持的浏览器,可以选择MutationObserver.

根据这一点,应该做的事情:

// callback executed when canvas was found
function handleCanvas(canvas) { ... }

// set up the mutation observer
var observer = new MutationObserver(function (mutations, me) {
  // `mutations` is an array of mutations that occurred
  // `me` is the MutationObserver instance
  var canvas = document.getElementById('my-canvas');
  if (canvas) {
    handleCanvas(canvas);
    me.disconnect(); // stop observing
    return;
  }
});

// start observing
observer.observe(document, {
  childList: true,
  subtree: true
});
Run Code Online (Sandbox Code Playgroud)

NB我自己没有测试过这段代码,但这是一般的想法.

您可以轻松地将其扩展为仅搜索已更改的DOM部分.为此,使用mutations参数,它是一个MutationRecord对象数组.

  • 喜欢这个。谢谢。 (2认同)
  • 这种模式在很多情况下确实很有帮助,特别是当您将 JS 拉入页面并且不知道是否加载其他项目时。 (2认同)

小智 22

一种更现代的等待元素的方法:

while(!document.querySelector(".my-selector")) {
  await new Promise(r => setTimeout(r, 500));
}
// now the element is loaded
Run Code Online (Sandbox Code Playgroud)

请注意,此代码需要包含在异步函数中.

  • 这很整洁! (7认同)

rdh*_*aut 15

如果您想要使用 MutationObserver 的通用解决方案,您可以使用此功能

// MIT Licensed
// Author: jwilson8767

/**
 * Waits for an element satisfying selector to exist, then resolves promise with the element.
 * Useful for resolving race conditions.
 *
 * @param selector
 * @returns {Promise}
 */
export function elementReady(selector) {
  return new Promise((resolve, reject) => {
    const el = document.querySelector(selector);
    if (el) {resolve(el);}
    new MutationObserver((mutationRecords, observer) => {
      // Query for elements matching the specified selector
      Array.from(document.querySelectorAll(selector)).forEach((element) => {
        resolve(element);
        //Once we have resolved we don't need the observer anymore.
        observer.disconnect();
      });
    })
      .observe(document.documentElement, {
        childList: true,
        subtree: true
      });
  });
}
Run Code Online (Sandbox Code Playgroud)

来源:https : //gist.github.com/jwilson8767/db379026efcbd932f64382db4b02853e
使用示例

elementReady('#someWidget').then((someWidget)=>{someWidget.remove();});
Run Code Online (Sandbox Code Playgroud)

注意:MutationObserver 有很好的浏览器支持;https://caniuse.com/#feat=mutationobserver

等等!:)


wLc*_*wLc 7

这是对Jamie Hutber的回答的一个小改进

const checkElement = async selector => {

while ( document.querySelector(selector) === null) {
    await new Promise( resolve =>  requestAnimationFrame(resolve) )
}

return document.querySelector(selector); };
Run Code Online (Sandbox Code Playgroud)


ncu*_*ica 6

中继requestAnimationFrame比中继更好setTimeout。这是我在es6模块中使用的解决方案Promises

es6,模块和承诺:

// onElementReady.js
const onElementReady = $element => (
  new Promise((resolve) => {
    const waitForElement = () => {
      if ($element) {
        resolve($element);
      } else {
        window.requestAnimationFrame(waitForElement);
      }
    };
    waitForElement();
  })
);

export default onElementReady;

// in your app
import onElementReady from './onElementReady';

const $someElement = document.querySelector('.some-className');
onElementReady($someElement)
  .then(() => {
    // your element is ready
  }
Run Code Online (Sandbox Code Playgroud)

plain js and promises

var onElementReady = function($element) {
  return new Promise((resolve) => {
    var waitForElement = function() {
      if ($element) {
        resolve($element);
      } else {
        window.requestAnimationFrame(waitForElement);
      }
    };
    waitForElement();
  })
};

var $someElement = document.querySelector('.some-className');
onElementReady($someElement)
  .then(() => {
    // your element is ready
  });
Run Code Online (Sandbox Code Playgroud)

  • 实际上,这不适用于当前形式。如果$ someElement最初为空(即DOM中尚不存在),则将该空值(而不是CSS选择器)传递给onElementReady函数,该元素将永远无法解析。相反,将CSS选择器作为文本传递,并尝试在每次传递时通过.querySelector获得对元素的引用。 (3认同)

小智 6

这是一个使用 observables 的解决方案。

waitForElementToAppear(elementId) {                                          

    return Observable.create(function(observer) {                            
            var el_ref;                                                      
            var f = () => {                                                  
                el_ref = document.getElementById(elementId);                 
                if (el_ref) {                                                
                    observer.next(el_ref);                                   
                    observer.complete();                                     
                    return;                                                  
                }                                                            
                window.requestAnimationFrame(f);                             
            };                                                               
            f();                                                             
        });                                                                  
}                                                                            
Run Code Online (Sandbox Code Playgroud)

现在你可以写

waitForElementToAppear(elementId).subscribe(el_ref => doSomethingWith(el_ref);
Run Code Online (Sandbox Code Playgroud)


Car*_*ela 5

您可以通过设置超时来检查 dom 是否已经存在,直到它已经在 dom 中呈现。

var panelMainWrapper = document.getElementById('panelMainWrapper');
setTimeout(function waitPanelMainWrapper() {
    if (document.body.contains(panelMainWrapper)) {
        $("#panelMainWrapper").html(data).fadeIn("fast");
    } else {
        setTimeout(waitPanelMainWrapper, 10);
    }
}, 10);
Run Code Online (Sandbox Code Playgroud)


Her*_*aña 5

Iftah的另一种变体

var counter = 10;
var checkExist = setInterval(function() {
  console.log(counter);
  counter--
  if ($('#the-canvas').length || counter === 0) {
    console.log("by bye!");
    clearInterval(checkExist);
  }
}, 200);
Run Code Online (Sandbox Code Playgroud)

以防万一元素从未显示,所以我们不会无限地检查。