开发者

Load external script dynamic, and access it, so I can trigger its domready function

开发者 https://www.devze.com 2022-12-26 07:09 出处:网络
I am trying to load the Zopim chat client. Normally it is included with a document write action. This causes it to be loaded before the domReady function is triggered, as it needs this to start itself

I am trying to load the Zopim chat client. Normally it is included with a document write action. This causes it to be loaded before the domReady function is triggered, as it needs this to start itself.

I want to load it later, and this works by using prototype (framework determined by Magento) to create a new script element and attaching it to the head. The script is loaded perfectly, but the domReady doesn't fire, so the script is never started.

The script is a nameless class, by this I mean that all its functions are encapsulated in {} UPDATE: Sorry, I got it wrong, it is as self invoking function, the same syntax as the first answer suggest. (function C(){ })();

This function call when run sets up listening events for the domReady event under various browsers and then waits. When the domready event fires, it calls a function (that is within the self-invoked function) that starts everything. What I need, is a way to access this function somehow. END UPDATE

Within that is a function named C.

How can I call this function directly?

Or put a开发者_Go百科nother way, how can I start an external javascript file that depends on domready going off, when that event doesn't happen?

Can I load an external javascript file into a variable, so I can name the class? Can I access the nameless class {} somehow maybe via the script tag? Is there a way to alter the external file/javascript so I can have it look for another event, one that I can trigger?

About the only solution I can think of at the moment is to create a iframe and load the script in that.


If you want to fire it after loading it asynchronously after the domready is already fired, you can do this:

Make your function C a self invoking function by:

(function C(){
})();

With this approach you would be changing the external script though.


You may trigger the event programmatically, for example:

window.dispatchEvent(new Event('DOMContentLoaded'));

See Creating and triggering events.

But note that this solution can be tricky to make it work correctly, cause when you trigger the event, some event handlers that have registered to the event will trigger a second time. And this causes problems like page not working as expected or an infinite loop (event registering, handler call, event registering, handler call indefinitely).

So you would need a solution to make sure that the different scripts that registered to the DOMContentLoaded event have their handlers only called 1 time exactly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号