Dynamic loading of a JavaScript file is different if I use appendChild () or jQuery.append ()

I am trying to dynamically load a JavaScript file by adding a script element to the head element, after which I check for the function defined inside this file to verify that the download was successful.

If I use this code:

var scriptElem = document.createElement("script");
scriptElem.type = "text/javascript";
scriptElem.src = 'myfile.js';
document.getElementsByTagName('head')[0].appendChild(scriptElem);

a new function is not defined subsequently. However, if I change the last line to use jQuery, like this:

$('head').append($(scriptElem));

this. In the first case, Firebug shows a new script element in the HTML tab as another key, while in the second case it is not.

I tried using jQuery.getScript () for this, but that didn't work either. Also, if that matters, the call is made from a function passed to jQuery using:

$(document).ready();

- , ?

+3
5

, jQuery . $('head'). Append (scriptElem); script, . , "function something() {};" , JQuery append(), native appendChild. (, .) , setTimeout (function() {alert (something)}, 1); . , JQuery script, .

, , domManip JQuery, :

if ( scripts ) {
   jQuery.each( scripts, evalScript );
}

:

function evalScript( i, elem ) {
    if ( elem.src ) {
        jQuery.ajax({
            url: elem.src,
            async: false,
            dataType: "script"
        });
    } else {
        jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
    }

    if ( elem.parentNode ) {
        elem.parentNode.removeChild( elem );
    }
}

, JQuery script, , JQuery , .

+1

jQuery, jQuery script .append(), evalScript():

function evalScript( i, elem ) {
    if ( elem.src ) {
        jQuery.ajax({
            url: elem.src,
            async: false,
            dataType: "script"
        });
    } else {
        jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
    }

    if ( elem.parentNode ) {
        elem.parentNode.removeChild( elem );
    }
}

, jQuery xhr script . append(). .appendChild() script , script , .

+1

!

$("myfile.js").getScript(function(){ /* do something */ });
0

. :

$.getScript("myfile.js", function(){ /* do something */ });
0

JavaScript, script, . , , , JavaScript.

JavaScript - , <script>, .

, jQuery JSAN JSModule, AJAX. JavaScript, . eval() , . , .

, , , , , .

0

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


All Articles