Vladimir Vladimir - 7 months ago 26
Javascript Question

How to set up Browsersync to correctly serve AJAX requests?

I'm trying to set up Browsersync for loading documents via AJAX.

All files are stored in the project root folder:

gulpfile.js
index.html
load-me.html


Simplified Browsersync settings

gulp.task('server', () =>

browserSync.init({
files: '*.html',
server: {
baseDir: './'
},
port: 9000,
notify: false
});
});


index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Try to load content via AJAX</title>
</head>
<body>

<button>Click me</button>
<div id="result"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script>
$(function(){
$('button').click(function(){
$('#result').load('load-me.html');
});
});
</script>

</body>
</html>


load-me.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Yay!</title>
</head>
<body>
<h1>10x, God. It's loaded!</h1>
</body>
</html>


When I start MAMP server everything works fine. But Browsersync settings are corrupted. And I can't fix it. Please, help, who knows.

Thanks in advance :)

Answer

This is because browser-sync modifies the response each time you request for an html page. The modified html page comes with a script that has a document.write. If you check your html source code you should see something like this:

<script id="__bs_script__">//<![CDATA[
    document.write("<script async src='/browser-sync/browser-sync-client.2.12.3.js'><\/script>".replace("HOST", location.hostname));
//]]></script>

This happens to occur for load-me.html page when requesting it in a browser-sync server as well. The modified html response that's inserted in the #result element will also have the script above inserted which runs the document.write all over again and thereby overriding the entire html page.

There are two options for the solution:

  1. Target specific html tags that you want to be inserted inside #result from the load-me.html html page by loading page fragments. Example below.

Javascript

$('#result').load('load-me.html h1');

The example above should only insert the h1 element inside the load-me.html page, and not the entire load-me.html html content.

  1. You can choose to only have the html contents that you need inside load-me.html without the html, and body tags.
Comments