Insert object (jquery) delay?

前端 未结 6 431
天命终不由人
天命终不由人 2021-01-12 21:49

I allow the user to insert an object, an image, and then i call a function on that object. What seems randomly to me, sometimes it works and sometimes not, I guess it has t

6条回答
  •  抹茶落季
    2021-01-12 22:49

    You can do it without jquery, just use the es5 mutation observer and a load event

    (function (global) {
        "use strict";
    
        if (!("MutationObserver" in global)) {
            global.MutationObserver = global.WebKitMutationObserver || global.MozMutationObserver;
        }
    
        function loadImage(e) {
            var img = e.target,
                width = img.clientWidth,
                height = img.clientHeight;
    
            img.removeEventListener('load', loadImage, false);
            alert("Image loaded: width: " + width + " height: " + height);
        }
    
        var observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                switch (mutation.type) {
                case 'childList':
                    Array.prototype.forEach.call(mutation.target.children, function (child) {
                        if (child.id === "smiley") {
                            child.addEventListener('load', loadImage, false);
                        }
                    });
    
                    break;
                default:
                }
            });
        });
    
        var container = document.getElementById("container");
    
        observer.observe(container, {
            childList: true,
            characterData: true,
            subtree: true
        });
    
        container.innerHTML = "";
    }(window));
    

    A live example is on jsfiddle

    You can read more about MutationObserver at mdn

提交回复
热议问题