Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Browsersync reload browser before running styles #282

Closed
ashussen opened this issue Sep 28, 2017 · 32 comments
Closed

Browsersync reload browser before running styles #282

ashussen opened this issue Sep 28, 2017 · 32 comments

Comments

@ashussen
Copy link

I run gulp browsersync.

But unexpectedly it reloads the page before running the styles script. The most recent changes I made is not applied.

I need to either save it twice or reload the browser manually.
How to reload the browser after it compiles the styles?

Here is the log:

Browsersync] Reloading Browsers...
[16:22:32] Starting 'styles'...
[Browsersync] 4 files changed (login.css.map, login.css, style.css.map, style.css)
[16:22:34] Finished 'styles' after 1.83 s
@jackfearing
Copy link

+1

@jackfearing
Copy link

Just checking to see if anybody has solved this yet?

@ashussen
Copy link
Author

Nope, hasn't been solved. Hence, the v5 is now officially published.

@garretthyder
Copy link
Collaborator

Can you share your gulpfile please

@jackfearing
Copy link

jackfearing commented Nov 10, 2017

Sure -- attached is my gulpfile which I needed to convert to txt so I could upload to git.

gulpfile.js.txt

@garretthyder
Copy link
Collaborator

Thanks @jackfearing,
I don't code much gulp but from the documentation I don't see stream as an option on reload like the gulpfile has here;

.pipe(browserSync.reload({
     stream: true
}));

In the browsersync doc they mention use of stream for css and reload for html file changes;
Stream - https://www.browsersync.io/docs/api#api-stream
Reload - https://browsersync.io/docs/api#api-reload

Following the documented example here;
https://browsersync.io/docs/gulp
Can you try amending all instances of the reload stream code snippet I quoted above, I think it's in login and styles, with the following;

.pipe(browserSync.stream());

Let me know what your output is, and if that's the case I'll create a PR.

Cheers
Another resource mentioning this .stream() function without the reload wrapping it was here;
http://paulsalaets.com/posts/injecting-styles-in-page-with-browser-sync

@jackfearing
Copy link

jackfearing commented Nov 14, 2017

Unfortunately I still see same issue. Is there something else I could try? Attached is my revised gulp file if that helps...

gulpfile.js.zip

@garretthyder
Copy link
Collaborator

Sorry @jackfearing that's frustrating. The stream shouldn't reload the browser but instead just inject the css. If that's not happening maybe try debug logging to get more verbose information.

But I found several other similar threads saying might be permissions, etc. Or maybe just instead of stream do a reload to force reload as the inject doesn't seem to work.

Some threads to go through and attempt;
BrowserSync/browser-sync#955
BrowserSync/browser-sync#943
BrowserSync/browser-sync#601
BrowserSync/gulp-browser-sync#26

I saw @JeremyEnglert on one, Jeremy did you have any luck with your issue as it seems similar.

Thanks

@jackfearing
Copy link

Thanks -- for the force reload, are you taking about just loading the browser manually or is there a force reload browser sync snippet?

@jackfearing
Copy link

Garrett - do you think the issue could be caused by browser caching?

@garretthyder
Copy link
Collaborator

@jackfearing for switching to reload over stream try switching .pipe(browserSync.stream()); to .pipe(browserSync.reload());

@garretthyder
Copy link
Collaborator

As to browser caching I don't believe the Header tags get injected when using Browsersync but had to say. You can try a manual reload but that defeats the purpose.
Are you doing this locally or on a server?
Might want to check those threads specifically for the permissions issue as that's been mentioned as a problem.

Other than that updating to latest gulp, browsersync and browser (chrome, etc) might work. But I'm at a loss beyond that sadly

@jackfearing
Copy link

jackfearing commented Nov 14, 2017

Not sure if tis is the solution but I did try disabling Chrome's browser cache and the issue goes away. I would probably need a 3rd party with the same issue to verify. If that works I'm wondering if there is a gulp setting and/or plugin that would do the job rather than having to go into each browser and adjusting the setting.

Select the “Menu” button in the upper-right corner, then select “More tools” > “Developer tools“. You can also get to this screen by pressing Ctrl + Shift + I for Windows and Linux or Command + Option + I for Mac OS X.
The Dev Tools window appears. Select “Network”,
Check the “Disable cache” box.

chrome-disable-cache

@garretthyder
Copy link
Collaborator

Thanks @jackfearing so it is a browser caching thing. I read a few things about it being known or looked at by BrowserSync but that was in 2015 so not sure if corrected. Maybe update your version of browsersync?

The other thought was in the BrowserSync init where you disabled notify maybe set injectChanges to true;
https://browsersync.io/docs/options#option-injectChanges

@jackfearing
Copy link

That seems to work in Chrome. Maybe the issue is Safari and caching... regardless I think this is a good solution for now. Thanks for all your help!

@garretthyder
Copy link
Collaborator

Awesome glad to hear you're working. Now we'll just need @ashussen to confirm

@ashussen
Copy link
Author

Hi Garret, Jack,

Thank you for sparing some time to look at this. But it still doesn't work in my case.
I have always ticked the 'Disable cache' on chrome, also I tried some changes you suggest.
browserSync.stream() -> turns out exactly the same
browserSync.reload() -> show an error "Can't pipe to undefined"

I think the problem is BrowserSync try to reload the browser before the styles been compiled.
See below is the log I have when running BrowserSync:

[Browsersync] Reloading Browsers...
[12:03:56] Starting 'styles'...
[Browsersync] 4 files changed (login.css.map, login.css, style.css.map, style.css)
[12:03:58] Finished 'styles' after 2.06 s

@garretthyder
Copy link
Collaborator

Can you share your Gulpfile @ashussen and I'll see if there's anything unique with yours. Cheers

@ashussen
Copy link
Author

@garrett-eclipse No, nothing different with my Gulpfile.js. I just tried it again yesterday with a fresh install from the master branch.

I managed to get it working, and doing some improvements for my workflow.
But the main problem is the browser reloaded, then there is a few seconds gap from the page loaded and 'Connected to BrowserStack' process. Eventually, the browserSync.stream() process happens in the few seconds gap then no changes are seen on the first reload.

My fix is, removing the first reload, and just let browserSync.stream() do the CSS injection. I removed the files on the first parameters on browserSync.init().

    browserSync.init({
            proxy: LOCAL_URL,
    });

@garretthyder
Copy link
Collaborator

Nice @ashussen I'm glad it's working for you now. I'll leave this ticket to @JeremyEnglert to review and see if the master gulpfile.js requires a modification. Cheers

@jackfearing
Copy link

So @ashussen, basically the css is injecting without refresh but you still have the issue of the page not reloading -- correct?

@jackfearing
Copy link

jackfearing commented Nov 22, 2017

One thing you might want to try is adding a reloadDelay to the browserSync.init like so. It seems to work with the 'files' parameter in the function.

browserSync.init(files, { proxy: LOCAL_URL, notify: false, injectChanges: true, // Open the site in Chrome & Firefox //browser: ["google chrome", "firefox"], reloadDelay: 250, });

@ashussen
Copy link
Author

@jackfearing Yes. My current solution is in these 3 cases:

  • Inject CSS if any .scss modified
  • Reload browser if .js modified
  • Reload browser if .php modified

Works fine for me. Thanks for your suggestion for the delay. I will try the code.

Also, I noticed, that the Image minified is buggy as well. If you run browsersync, then paste a new image on assets/images folder. Then unlimited loop on runs on browsersync.

@jackfearing
Copy link

Can you post your working gulp file so I could compare with mine?

@ashussen
Copy link
Author

Hi @jackfearing,

Here is gist for my gulpfile.js
https://gist.github.com/ashussen/27c9fd2eaf050cceb3c2ffc293a5386f

@garretthyder
Copy link
Collaborator

I think the styles not injecting/reloading is due to this outdated format in the styles section;

.pipe(browserSync.reload({
    stream: true
}));

I suggest replacing with either the new stream call or the reload without stream params;
stream - .pipe(browserSync.stream());
reload - .pipe(browserSync.reload());

Hope that's of some help

@ashussen
Copy link
Author

ashussen commented Dec 4, 2017

@garrett-eclipse Thanks for your suggestion, but as I mentioned before. I tried both cases, but no luck on those.

@marc-squarewave
Copy link

marc-squarewave commented Dec 5, 2017

I was having the same issue. Commenting out SOURCE.styles in the files array helped for me.
Isn't it redundant to watch styles since we're also watching and processing the SCSS which is nested in /styles?

`// Browser-Sync watch files and inject changes
gulp.task('browsersync', function() {

// Watch these files
var files = [
	//SOURCE.styles, 
	SOURCE.scripts,
	SOURCE.images,
	SOURCE.php,
];

browserSync.init(files, {
    proxy: LOCAL_URL,
});

gulp.watch(SOURCE.styles, gulp.parallel('styles'));
gulp.watch(SOURCE.scripts, gulp.parallel('scripts')).on('change', browserSync.reload);
gulp.watch(SOURCE.images, gulp.parallel('images'));

});`

@jackfearing
Copy link

Tagging up on m72 comment above, below is my latest gulp file which seems to do the trick. All the styles get injected rather then having the page reload however if the page / templates are changed, only then does the page reload.

`// GULP PACKAGES
// Most packages are lazy loaded
var gulp = require('gulp'),
gutil = require('gulp-util'),
browserSync = require('browser-sync').create(),
filter = require('gulp-filter'),
plugin = require('gulp-load-plugins')();

// GULP VARIABLES
// Modify these variables to match your project needs

// Set local URL if using Browser-Sync
const LOCAL_URL = 'http://your_site_here';

// Set path to Foundation files
const FOUNDATION = 'node_modules/foundation-sites';

// Select Foundation components, remove components project will not use
const SOURCE = {
scripts: [
// Lets grab what-input first
'node_modules/what-input/dist/what-input.js',

	// Foundation core - needed if you want to use any of the components below
	FOUNDATION + '/dist/js/plugins/foundation.core.js',
	FOUNDATION + '/dist/js/plugins/foundation.util.*.js',

	// Pick the components you need in your project
	//FOUNDATION + '/dist/js/plugins/foundation.abide.js',
	FOUNDATION + '/dist/js/plugins/foundation.accordion.js',
	FOUNDATION + '/dist/js/plugins/foundation.accordionMenu.js',
	//FOUNDATION + '/dist/js/plugins/foundation.drilldown.js',
	//FOUNDATION + '/dist/js/plugins/foundation.dropdown.js',
	FOUNDATION + '/dist/js/plugins/foundation.dropdownMenu.js',
	FOUNDATION + '/dist/js/plugins/foundation.equalizer.js',
	FOUNDATION + '/dist/js/plugins/foundation.interchange.js',
	FOUNDATION + '/dist/js/plugins/foundation.smoothScroll.js',
	FOUNDATION + '/dist/js/plugins/foundation.magellan.js',
	FOUNDATION + '/dist/js/plugins/foundation.offcanvas.js',
	//FOUNDATION + '/dist/js/plugins/foundation.orbit.js',
	FOUNDATION + '/dist/js/plugins/foundation.responsiveMenu.js',
	FOUNDATION + '/dist/js/plugins/foundation.responsiveToggle.js',
	FOUNDATION + '/dist/js/plugins/foundation.reveal.js',
	//FOUNDATION + '/dist/js/plugins/foundation.slider.js',
	FOUNDATION + '/dist/js/plugins/foundation.sticky.js',
	FOUNDATION + '/dist/js/plugins/foundation.tabs.js',
	FOUNDATION + '/dist/js/plugins/foundation.responsiveAccordionTabs.js',
	//FOUNDATION + '/dist/js/plugins/foundation.toggler.js',
	//FOUNDATION + '/dist/js/plugins/foundation.tooltip.js',
	FOUNDATION + '/dist/js/plugins/foundation.util.motion.js',

	// Place custom JS here, files will be concantonated, minified if ran with --production
	'assets/scripts/js/**/*.js',

	// Exclude scripts in the JS folder by placing an ! in front of the directory path
	// Re-run "npm run scripts" or "npm run build"
	// Then re-run "npm run browsersync"
	'!assets/scripts/js/sticky-footer.js',
	'!assets/scripts/js/aos.js',
],

// Scss files will be concantonated, minified if ran with --production
styles: 'assets/styles/scss/**/*.scss',

// Scss files will be concantonated, minified if ran with --production
login: 'assets/styles/scss/login.scss',

// Images placed here will be optimized
images: 'assets/images/**/*',

php: '**/*.php'

};

const ASSETS = {
styles: 'assets/styles/',
login: 'assets/styles/',
scripts: 'assets/scripts/',
images: 'assets/images/',
all: 'assets/'
};

const JSHINT_CONFIG = {
"node": true,
"globals": {
"document": true,
"jQuery": true
}
};

// GULP FUNCTIONS
// JSHint, concat, and minify JavaScript
gulp.task('scripts', function() {

// Use a custom filter so we only lint custom JS
const CUSTOMFILTER = filter(ASSETS.scripts + 'js/**/*.js', {restore: true});

return gulp.src(SOURCE.scripts)
	.pipe(plugin.plumber(function(error) {
        gutil.log(gutil.colors.red(error.message));
        this.emit('end');
    }))
	.pipe(plugin.sourcemaps.init())
	.pipe(plugin.babel({
		presets: ['es2015'],
		compact: true,
		ignore: ['what-input.js']
	}))
	.pipe(CUSTOMFILTER)
		.pipe(plugin.jshint(JSHINT_CONFIG))
		.pipe(plugin.jshint.reporter('jshint-stylish'))
		.pipe(CUSTOMFILTER.restore)
	.pipe(plugin.concat('scripts.js'))
	.pipe(plugin.uglify())
	.pipe(plugin.sourcemaps.write('.')) // Creates sourcemap for minified JS
	.pipe(gulp.dest(ASSETS.scripts))

});

// Compile Sass, Autoprefix and minify
gulp.task('styles', function() {
return gulp.src(SOURCE.styles)
.pipe(plugin.plumber(function(error) {
gutil.log(gutil.colors.red(error.message));
this.emit('end');
}))
.pipe(plugin.sourcemaps.init())
.pipe(plugin.sass())
.pipe(plugin.autoprefixer({
browsers: [
'last 2 versions',
'ie >= 9',
'ios >= 7'
],
cascade: false
}))
.pipe(plugin.cssnano())
.pipe(plugin.sourcemaps.write('.'))
.pipe(gulp.dest(ASSETS.styles))
.pipe(browserSync.stream());
});

// Compile Sass (Login), Autoprefix and minify
gulp.task('login', function() {
return gulp.src(SOURCE.login)
.pipe(plugin.plumber(function(error) {
gutil.log(gutil.colors.red(error.message));
this.emit('end');
}))
.pipe(plugin.sourcemaps.init())
.pipe(plugin.sass())
.pipe(plugin.autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(plugin.cssnano())
.pipe(plugin.sourcemaps.write('.'))
.pipe(gulp.dest(ASSETS.styles))
.pipe(browserSync.stream());
});

// Optimize images, move into assets directory
gulp.task('images', function() {
return gulp.src(SOURCE.images)
.pipe(plugin.newer(ASSETS.images))
.pipe(plugin.imagemin())
.pipe(gulp.dest(ASSETS.images))
});

gulp.task( 'translate', function () {
return gulp.src( SOURCE.php )
.pipe(plugin.wpPot( {
domain: 'jointswp',
package: 'Example project'
} ))
.pipe(gulp.dest('file.pot'));
});

// Browser-Sync watch files and inject changes
gulp.task('browsersync', function() {

// Watch these files (add SOURCE VARS below to var files for full reload instead on injecting)
	//SOURCE.styles,
	//SOURCE.login,
	//SOURCE.scripts,
	//SOURCE.images,
var files = [
	SOURCE.php,
];
// If the files, is removed the page would reload but the scripts will inject via browser.sync stream
browserSync.init(files, {
    proxy: LOCAL_URL,
    notify: false,
    injectChanges: true,
    // Open the site in Chrome & Firefox
	//browser: ["google chrome", "firefox"],
	reloadDelay: 250,
});

gulp.watch(SOURCE.styles, gulp.parallel('styles'));
gulp.watch(SOURCE.login, gulp.parallel('login'));
gulp.watch(SOURCE.scripts, gulp.parallel('scripts')).on('change', browserSync.reload);
gulp.watch(SOURCE.images, gulp.parallel('images'));

});

// Watch files for changes (without Browser-Sync)
gulp.task('watch', function() {

// Watch .scss files
gulp.watch(SOURCE.styles, gulp.parallel('styles'));

// Watch .scss files
gulp.watch(SOURCE.login, gulp.parallel('login'));

// Watch scripts files
gulp.watch(SOURCE.scripts, gulp.parallel('scripts'));

// Watch images files
gulp.watch(SOURCE.images, gulp.parallel('images'));

});

// Run styles, scripts and foundation-js
gulp.task('default', gulp.parallel('styles', 'login', 'scripts', 'images'));`

@MrSpecific
Copy link

+1 for @m72 's solution - I was experiencing the same behavior as OP, and this fixed it for me. Thank you!

garretthyder pushed a commit to garretthyder/JointsWP that referenced this issue Dec 13, 2017
To resolve the browsersync issues outlined in JeremyEnglert#282 I've removed the styles, scripts and images from the files array as they're being watched separately and the double-watching causes users reloading issues.
@garretthyder
Copy link
Collaborator

Thanks everyone, I've created PR #303 to correct this. As I don't have an instance of this issue can I get some testers/reviewers from this thread to look at it please.
I removed styles, scripts and images as they're all watched individually after the init so shouldn't need to be doubled down, I've left php as it's not watched specifically outside of init.

@JeremyEnglert
Copy link
Owner

Thanks everyone!

@garrett-eclipse's PR has been merged into the master branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants