When Loading an HTML Page via Ajax, Will Script Tags Be Loaded

When loading an html page via ajax, will script tags be loaded?

When you call the jQuery.ajax() method, you can specify the dataType property, which describes what kind of data you are expecting from the server, and how to handle it once it is received.

By default, jQuery will try to guess the dataType based on the MIME type of the response. However you can explicitly specify a dataType from the following:

  • html: Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

  • text: A plain text string.

  • xml: Returns a XML document that can be processed via jQuery.

  • script: Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used.

  • json: Evaluates the response as JSON and returns a JavaScript object.

  • jsonp: Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.

As an example, the following ajax call will return the data as a plain text string, without executing the scripts or manipulating the DOM:

$.ajax({
url: 'ajax/test.html',
dataType: 'text',
success: function(data) {
alert(data);
}
});

Loading script tags via AJAX

If you use jQuery's .html method it parses out the script tag and evals it:

$("div").html('<script type="text/javascript">alert("This should work")</script>');

If jQuery isn't an option you could write this yourself using either (1) a regular expression, or (2) parse out the DOM tree and find script tags. (#2 is how jQuery does it)

Handling script loading when loading page through Ajax

Since you are getting the full pages anyway it doesn't make sense to do that with ajax, especially when it breaks proper HTML. What you could do is to use an iframe to display your pages, and then manage them with some simple javascript in the parent document.

For example:

<!-- iframe for one of your pages -->
<iframe id="page-foo-iframe"
title="page foo"
width="100%"
height="100%"
src="/a_third_page">
</iframe>

<script>
/*
* You can have a button, or something else, call these functions
* whenever you need to show/hide a page.
*/
function showIframePage(id) {
let page = document.getElementById(id);
page.style.display = "block";
}

function hideIframePage(id) {
let page = document.getElementById(id);
page.style.display = "none";
}
</script>

I would also suggest that you look into using a framework, in particular the JS ones like Vue/React/Angular, because they will make handling things like this a lot simpler and easier to maintain. If you have to load full documents though, iframes are the best way to do that.

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

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);
}
}
$.ajax({
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++) {
callbacks.push(createGetScriptCallback(scriptsEl[i].getAttribute("src")));
}
$.when.apply($, callbacks)
.fail(function (xhr, status, err) {
console.error(status, err);
});
$('body').append(data);
}
});

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

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

Executing script injected by innerHTML after AJAX call

JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the src attribute of your script tag and voila, it loads and executes the external script.

This other StackOverflow post may also be helpful to you: Can scripts be inserted with innerHTML?.



Related Topics



Leave a reply



Submit