Javier del Saz Javier del Saz - 1 year ago 104
HTML Question

jQuery is not loading js file in script tag of ajax request

I have an ajax POST request, this request comes with html with

<script src="">
tags referencing external js files, when I insert this html in DOM the JS are not loaded, what I'm doing wrong? I can remember see this working loading the external script1 and script2 without problems.


type: 'POST',
dataType: 'xml/html',
cache: false,
url: "/html/with/scripttags",
data: {somedata:'value'},
success: function(data) {

Content loaded:

<link rel="stylesheet" media="all" href="http://domain.com/application.css" />
<script src='http://domain.com/script.js' type='text/javascript'></script>
<script src='http://domain.com/script2.js' type='text/javascript'></script>
<script type='text/javascript'>alert('executed')</script>

However the alert in script tag is is executed without problems and the
external file is loaded without problems. Looks like jQuery doesn't load the files, I also check the network tab..

Answer Source

That's jQuery's normal behaviour, if you want to include your scripts, you need to parse the html and add them manually.

Bad news: you can't even select script tags in strings with $()...

I didn't test that, but this quick and dirty example should work:

function createGetScriptCallback(url) {
  return function () {
    return $.getScript(url);
  type: 'POST',
  dataType: 'xml/html',
  cache: false,
  url: "/html/with/scripttags",
  data: {
    somedata: 'value'
  success: function (data) {
    var parser, doc, scriptsEl, callbacks;
    parser = new DomParser();
    doc = parser.parseFromString(data, "text/html")
    scriptsEl = doc.querySelectorAll("script[src]");
    callbacks = []
    for (var i = 0; i < scriptsEl.length; i++) {
    $.when.apply($, callbacks)
      .fail(function (xhr, status, err) {
        console.error(status, err);

But you should not depend on the html to load your scripts.

edit: less dirty code (inspired by @guest271314 's answer)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download