Where are the scripts loaded after ajax call? (Translate)

in the previous SO post , a solution was found to the problem of dynamically loading pages with embedded <script> tags. however, this was not a comprehensive solution, as I found. The script that breaks the code (view the previous post and its solution) looks something like this:

- svc.html -

 <script type="text/javascript" src="/plugin.js" css="/plugin.css"></script> <script type="text/javascript"> plugin_method(); </script> <div id='inner'> dynamically loaded content </div> 

where plugin.js looks the same as before, but contains a function definition for plugin_method .

The problem is that when a script node is added to the document:

 target[0].appendChild(scriptNode); 

code is not executed immediately. If (as in the previous post) on the svc.html page svc.html is only one script tag, everything is fine, but as soon as there is a second, $('script:last') in the plugin no longer indicates the correct script and, therefore, does not Loads a stylesheet.

in addition, the body of the second script tag seems to be executed before the search - in the code for the first, so the method call fails (because the function has not yet been defined).

I found a couple of links that I am considering:

http://requirejs.org/docs/why.html http://unixpapa.com/js/dyna.html

anybody ideas?

0
source share
1 answer

ok, so the answer is that we cannot just iterate over the list of scripts - we need to rewrite the inside of the load event, for example:

 // inspired by Kevin B suggestions // at: http://stackoverflow.com/questions/8234215/where-are-scripts-loaded-after-an-ajax-call (function ($) { $.fn.loadWithJs = function (o) { console.log(".loadWithJs - started"); var target = this; target.addScript = function (scripts, n, success) { var script = scripts[n]; var scriptNode = document.createElement('script'); for (var i = 0; i < script.attributes.length; i++) { var attr = script.attributes[i]; $(scriptNode).attr(attr.name, attr.value); } scriptNode.appendChild( document.createTextNode($(script).html()) ); $(scriptNode).load(function () { if (++n < scripts.length) target.addScript(scripts, n, success); else if (success) success(); }); target[0].appendChild(scriptNode); }; var success = o.success; o.success = function (html) { // convert script tags var h = $('<div />').append( html.replace(/<(\/)?script/ig, "<$1codex") ); // detach script divs from html var scripts = h.find("codex").detach(); // populate target target.html(h.children()); // start recursive loading of scripts target.addScript(scripts, 0, success); }; $.ajax(o); }; })(jQuery); 

* edit *

ok, that doesn't work either. If we add the script tag at the end of main.html , it will be added to the $ ('script') array before the first load event occurs (and before the scripts are run) and therefore $ ('script: last') is still not this way. GRR ...

0
source

Source: https://habr.com/ru/post/902158/


All Articles