简体   繁体   中英

Loading JavaScript after Angular.Js finished loading content

I need to load a part of the script after Angular finished loading all the content into the page.

Tried several directives, timeouts, evalAsync, however, there are still moments when the script is loaded before all the content is up.

Does anyone know a simple way to avoid this?

(the problem is that I'm using Sigma.Js which should load the graph visualization after the page finished loading. otherwise it loads it into a div 0 pixels high and thus is only shown when I resize the window or open a console in Chrome: http://www.knownodes.com/graph/aa1a2a78-b129-436c-8683-b4dd630f0566 )

This is easy in the synchronous case... simply do a setTimeout(0) from a root scope watcher to run after the digest cycle (or use the private and undocumented $$postDigest registration).

The problem is real apps, and it sounds like your app, has at least some degree of asynchronicity going on. I can think of two main kinds -- loading templates and fetching data. What you want is to run your code after all pending Ajax calls are finished and a digest cycle is completed.

Do I know a simple way? No. But you could add an $http interceptor that keeps a count of how many pending Ajax calls there are. When it gets to 0 you know all the data is back. See the Interceptors section here: http://docs.angularjs.org/api/ng.$http

This assumes you use $http or $resource (which indirectly uses $http). As for templates, assuming you aren't preloading the template cache by compiling them to JS ahead of time, I don't know if fetching templates uses the same $http interface and is therefore interceptable. Hopefully it does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM