Настройка livereload для firefox

What is LiveReload?

To use LiveReload, you need a client (this script) in your browser and a server running on your development machine.


This repository (livereload.js) implements the client side of the protocol. The client connects to a LiveReload server via web sockets and listens for incoming change notifications. When a CSS or an image file is modified, it is live-refreshed without reloading the page. When any other file is modified, the page is reloaded.

The server notifies the client whenever a change is made. Available servers are:

  • rack-livereload
  • guard-livereload
  • grunt-contrib-watch
  • python-livereload
  • more available on Google 🙂

If you are a web developer looking to use LiveReload, you should refer to your LiveReload server/app/tool’s documentation, rather that this repository. You should use the copy of livereload.js script bundled with your server, because it’s guaranteed to be compatible, and may be customized for that server.

Most LiveReload server vendors will serve livereload.js on the LiveReload port. When your server is running, you can typically access the script at .

Please read on only if you are:

  • using a server that doesn’t document the usage of livereload.js
  • interested in hacking on livereload.js or want to understand it better
  • developing a LiveReload server

Библиотека if-ie.styl

согласно БЭМ

if-ie.styl

Дополнительные возможности if-ie.styl

  1. В обоих файлах нужно подключать библиотеку до всех остальных стилей, и обязательно оба раза. (Может показаться, что хватило бы только первого — ведь таблица стилей для IE уже содержит основную таблицу стилей — но тогда некоторые последующие возможности не будут работать). В этом файле уже определяется , и поэтому в основной таблице стилей не нужно это явно прописывать.
  2. В таблице стилей для IE пропало условие — это показана работа первой фичи библиотеки: свойство автоматически появится только в таблице стилей для IE. Конечно, и в обычных браузерах можно использовать это свойство, но на практике такая необходимость случается крайне редко, так что можно облегчить основную таблицу стилей хотя бы чуть-чуть.

3 ответа 3

Одним из решений может быть выкинуть сервер LiveReload, который поддерживает пакет для Sublime Text. Это не единственная реализация LiveReload-сервера.

Есть также guard-livereload : плагин для системы Guard для выполнения действий при изменении файлов. Он написан на Ruby и потому для работы требует установленного Ruby. Порядок установки минимально отличается от других плагинов для Guard, вроде guard-haml , об установке и запуске которого я уже писал ранее.

В Guardfile можно задать шаблоны путей, изменение файлов по которым даст сигнал клиенту LiveReload для обновления. В README есть пример:

Код выше, разумеется, на Ruby. Каждая строчка watch добавляет на отслеживание пути, подходящие под регулярное выражение, относительно корня проекта (рабочей директории, где запущен guard ). Регулярка записывается /так/ , %r , или другими способами. Само выражение можно проверить на Rubular или просто в Interactive Ruby (IRB).

Guard можно загрузить и другими задачами, связанными с реакцией на изменение файлов. См. список плагинов Guard.

источник

What is LiveReload?

To use LiveReload, you need a client (this script) in your browser and a server running on your development machine.

This repository (livereload.js) implements the client side of the protocol. The client connects to a LiveReload server via web sockets and listens for incoming change notifications. When a CSS or an image file is modified, it is live-refreshed without reloading the page. When any other file is modified, the page is reloaded.

The server notifies the client whenever a change is made. Available servers are:

  • more available on Google 🙂

If you are a web developer looking to use LiveReload, you should refer to your LiveReload server/app/tool’s documentation, rather that this repository. You should use the copy of livereload.js script bundled with your server, because it’s guaranteed to be compatible, and may be customized for that server.

Most LiveReload server vendors will serve livereload.js on the LiveReload port. When your server is running, you can typically access the script at .

Please read on only if you are:

  • using a server that doesn’t document the usage of livereload.js
  • interested in hacking on livereload.js or want to understand it better
  • developing a LiveReload server

Using the originalPath option

You can map local CSS files to a remote URL. If your HTML file specifies live CSS files at like this:

<!-- html -->
<head>
  <link rel="stylesheet" href="http://domain.com/css/style.css">
</head>

Then you can tell livereload to substitute a local CSS file instead:

// server.js
var server = livereload.createServer({
    originalPath: "http://domain.com"
});
server.watch('/User/Workspace/test');

Then run the server:

When is modified, the stylesheet will be reloaded on the page.

Developing livereload

This library is implemented in CoffeeScript 1.x. It may eventually be converted to JavaScript, but because there are many projects that depend on this library, the conversion isn’t a priority.

To build the distributable versions, run .

Run to run the test suite.

Contributing

Contributions welcome, but remember that this library is meant to be small and serve its intended purpose only. Before submitting a pull request, open a new issue to discuss your feature or bug. Please check all open and closed issues.

When submitting code, please keep commits small, and do not modify the README file. Commit both the Coffee and JS files.

Changelog

0.9.1

  • Fix issue with livereload.js not resolving properly on some projects (caseywebdev)
  • Update license to newer style to suppress «no license» messages.
  • Update test scripts to handle compilers properly, suppressing the deprecation notice
  • Deprecating the tasks for building the project.

0.9.0

  • Serve Livereload client library from an NPM dependency instead of copying the code into the project — smhg
  • Update Chokidar to 3.3.0 which improves performance and reduces CPU load.

0.8.2

  • Fix regression in 0.8.1 where broadcasting failed due to incompatibility between arrays and sets
  • Add debug message when broadcasting to each socket
  • Add debug message for the message from clients

0.7.0

  • Updates bundled Livereload.js file to v2.3.0 to fix console error.
  • BREAKING CHANGE: The and options now replace the default extensions.
  • Adds the and options to preserve the old behavior of adding extensions to watch.
  • You can now use in your code to catch the «port in use» message gracefully. The CLI now handles this nicely as well.

0.6.3

  • Updated to use Chokidar 1.7, which hopefully fixes some memory issues.
  • BUGFIX: Check to see if a object is actually defined before attempting to close.
  • Added deprecation warning for option. In the next version, extensions you specify on the command line will OVERRIDE the default extensions. We’ll add a new option for adding your exts to the defaults.
  • Modified CLI so it trims spaces from the extensions in the array, just in case you put spaces between the commas.

0.6.2

  • CLI now properly splits extension list. Previous versions appended a blank entry to the list of extensions.
  • CLI now requires extensions to be comma separated instead of space separated.
  • Added extra debugging info (protocol version, watched directory, extensions, and exclusions).
  • Cleaned up some inconsistencies in the code.

0.6.0

  • Implements LiveReload protocol v7 so browser plugins work again.
  • Removes support for protocol v6
  • Introduces option
  • Introduces optional callback which will be invoked when the LiveReload server is listening

0.4.0

  • Rewritten using Chokidar library and library
  • Added option
  • Added support for specifying additional extensions from the CLI

Older version history not kept.

Released under the MIT license. See for details.

String substitution

The following substitutions are available for use in command line-related string values:

  • $(ruby) — path to the Ruby interpreter executable (the one chosen in Compilation Options for this project)
  • $(node) — path to the Node.js executable
  • $(plugin) — root of the plugin folder (e.g. you’d have $(plugin)/manifest.json file there)
  • $(project_dir) — folder added to LiveReload
  • $(additional) — any additional arguments specified in Compilation Options (note that although you include this as a single command line array item, it will actually be expanded to multiple arguments)

Source file:

  • $(src_file) — file NAME only (no path)
  • $(src_path) — full file path
  • $(src_rel_path) — file path relative to the project folder
  • $(src_dir) — parent directory of the file

Output file:

  • $(dst_file) — file NAME only (no path)
  • $(dst_path) — full file path
  • $(dst_rel_path) — file path relative to the project folder
  • $(dst_dir) — parent directory of the file

In import file mappings, the only available substitution variable is:

$(file) — the string captured by the first capture group of the import regular expression

Как создать свой сайт

Есть такое понятие «Live Reload» — это автоматическое обновление страницы в браузере, когда изменился составляющий её css-файл (html, js и т.д.). На практике это выглядит так: вебмастер внес изменения в css-файле, сохранил, браузер автоматом обновил страницу. То есть если по простому, то не нужно каждый раз нажимать кнопку «Обновить страницу» в браузере.

Чтобы реализовать Live Reload для своих задач потребуется совсем немного.

Занявшись этим вопросом, я решил убить сразу несколько зайцев. Проанализировав свою работу, я выстроил типовую последовательность действий:

  • внесение изменений в исходный код
  • сохранение (Ctrl+S)
  • переключение на окно браузера
  • обновление страницы (F5)
  • переключение обратно и повтор

Первое, что я решил сделать — избавиться от постоянного Ctrl+S. В Notepad++ (самый лучший редактор для вебмастера) достаточно установить плагин AutoSave. Идём в Плагины — Plugin Manager — Show Plugin Manager, отмечаем AutoSave и жмём Install.

После перезагрузки редактора в Плагинах появится пункт «Auto Save», где можно его настроить:

Главное выставить опцию «loses focus», поскольку она будет ключевой в Live Reload.

Итак, первая задача — избавиться от постоянного Ctrl+S — выполнена.

Для второй части нам потребуется установить расширение для FireFox «AutoReload». В настройках расширения следует отметить «Enabled». Остальные опции на своё усмотрение.


Для удобства работы, кнопку AutoReload лучше вынести в верхнюю панель браузера.

Теперь следует указать AutoReload какие файлы нужно отслеживать. Можно указать как конкретные файлы (Watch Files. ) либо указать каталог (Watch Directory. ) где находятся отслеживаемые файлы.

Важный момент — указывать отслеживаемые файлы нужно на открытой странице, той которая будет автообновляться. То есть открываем страницу, выбираем каталог, AutoReload автоматом найдет все файлы и жмём OK.

Собственно, это всё. Теперь работа сводится к двум пунктам:

  • правка кода
  • переключение на браузер

Если у вас один монитор, то иногда будет удобным одновременно видеть и страницу и исходный код. В Notepad++ этот вопрос решается очень просто. Нужно лишь выставить режим «Поверх всех окон», что позволит избежать скрытия окна редактора, а пункт меню «Только текст (во всё окно)» оставит только текст, без панелей. Для удобства можно назначить этим пунктам горячие клавиши, тогда переключение будет мгновенным.

Из минусов AutoReload отмечу только то, что он отслеживает файлы, указанные в момент добавления. Если появился новый файл, то он его уже не видит. Решается это достаточно просто — добавляем файлы ещё раз.

В целом отмечу, что метод годится для самых разных задач вебмастера. Я его оттестировал на CSS/JS/HTML/PHP файлах — работает без проблем.

источник

License

Copyright 2012–2015, Andrey Tarantsov — andrey@tarantsov.com

Purchasing policy notice: All users of the software are expected to purchase a license from Andrey Tarantsov unless they have a good reason not to pay. Users that don’t purchase a license are encouraged to apply for a free one at support@livereload.com. The users are free to:

  • download, build and modify the app;
  • share the modified source code;
  • share the purchased or custom-built binaries (with unmodified license and contact info), provided that the purchasing policy is explained to all potential users.

This software is available under the Open Community Indie Software License:

Permission to use, copy, modify, and/or distribute this software for any purpose is hereby granted, free of charge, subject to the following conditions:

  • all copies retain the above copyright notice, the above purchasing policy notice and this permission notice unmodified;

  • all copies retain the name of the software (LiveReload), the name of the author (Andrey Tarantsov) and the contact information (including, but not limited to, pointers to support@livereload.com and livereload.com URLs) unmodified;

  • no fee is charged for distibution of the software;

  • when distributing the software, the best effort is made to explain the purchasing policy to all users of the software who don’t already have a license.

In the event that no new official binary releases of the software are published for two consecutive years, the above conditions are permanently waived, and the software is additionally made available under the terms of the MIT license.

THE SOFTWARE IS PROVIDED «AS IS» AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

License

Copyright 2012–2015, Andrey Tarantsov — andrey@tarantsov.com

Purchasing policy notice: All users of the software are expected to purchase a license from Andrey Tarantsov unless they have a good reason not to pay. Users that don’t purchase a license are encouraged to apply for a free one at support@livereload.com. The users are free to:

  • download, build and modify the app;
  • share the modified source code;
  • share the purchased or custom-built binaries (with unmodified license and contact info), provided that the purchasing policy is explained to all potential users.

This software is available under the Open Community Indie Software License:

Permission to use, copy, modify, and/or distribute this software for any purpose is hereby granted, free of charge, subject to the following conditions:

  • all copies retain the above copyright notice, the above purchasing policy notice and this permission notice unmodified;

  • all copies retain the name of the software (LiveReload), the name of the author (Andrey Tarantsov) and the contact information (including, but not limited to, pointers to support@livereload.com and livereload.com URLs) unmodified;

  • no fee is charged for distibution of the software;

  • when distributing the software, the best effort is made to explain the purchasing policy to all users of the software who don’t already have a license.

In the event that no new official binary releases of the software are published for two consecutive years, the above conditions are permanently waived, and the software is additionally made available under the terms of the MIT license.

THE SOFTWARE IS PROVIDED «AS IS» AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Using livereload.js

This script is meant to be included into the web pages you want to monitor, like this:

LiveReload 2 server listens on port and serves livereload.js over HTTP (besides speaking the web socket protocol on the same port).

A slightly smarter way is to use the host name of the current page, assuming that it is being served from the same computer. This approach enables LiveReload when viewing the web page from other devices on the network:

<script>document.write('<script src="http://'
    + location.host.split(':')
    + ':35729/livereload.js"></'
    + 'script>')</script>

However, since is empty for URLs, we need to account for that:

<script>document.write('<script src="http://'
    + (location.host || 'localhost').split(':')
    + ':35729/livereload.js"></'
    + 'script>')</script>

LiveReload.js finds a tag that includes and uses it to determine the hostname/port to connect to. It also understands some options from the query string: , , , and .

specifies a version of the snippet, so that we can warn when the snippet needs to be updated. The currently recommended is version 1:

<script>document.write('<script src="http://'
    + (location.host || 'localhost').split(':')
    + ':35729/livereload.js?snipver=1"></'
    + 'script>')</script>

Additionally, you might want to specify and , which is minimum and maximum reconnection delay in milliseconds (defaulting to and ).

Alternatively, instead of loading livereload.js from the LiveReload server, you might want to include it from a different URL. In this case, add a parameter to override the host name. For example:

<script src="https://github.com/livereload/livereload-js/raw/master/dist/livereload.js?host=localhost"></script>

Options

Options can either be specified as query parameters of the tag’s source URL, or as a global dictionary. If the dictionary is specified, does not even try looking for its tag.

The set of supported options is the same for both methods:

  • : the host that runs a LiveReload server; required if specifying , otherwise will be autodetected as the origin of the tag
  • : optional server port override
  • : optional path to livereload server (default: ‘livereload’)
  • , : range of reconnection delays (if cannot connect to the server, it will attempt to reconnect with increasing delays); defaults to 1,000 ms minimum and 60,000 ms maximum
  • : timeout for a protocol handshake to be completed after a connection attempt; mostly only needed if you’re running an interactive debugger on your web socket server
  • : reload chrome runtime instead of page when true (default: false)
  • : prevent reload of CSS when changed stylesheet isn’t found in page (default: true)
  • : overrides plugins launch order; for details see below

By default LiveReload runs external plugins one by one, then tries live CSS reloading, live IMG reloading, reloads chrome extension and as a last resort reloads the whole page, if no plugin matched the updated file name. So, by default assume .

Alternatively, you can define to match your workflow.


If you’re using object on page, then define array of plugins:

var LiveReloadOptions ={...,    pluginOrder'css','img',    pluginOrder'css img'.split('')}

If you’re configuring LivReload using tag, then use following syntax:

<scriptsrc="//livereload.js?pluginOrder=css,img">

This means LiveReload will only try to do live and reloading, regardless of any external plugins.

You can specify external plugins order by adding each plugin id into or just use to run all external plugins in default order.

API & Variables

These options can either be set through or .

Creates a stream which notifies the livereload server on what changed.

Starts a livereload server. It takes an optional options parameter that is the same as the one noted above. Also you dont need to worry with multiple instances as this function will end immediately if the server is already runing.

Alternatively, you can call this function to send changes to the livereload server. You should provide either a simple string or an object, if an object is given it expects the object to have a property.

You can also tell the browser to refresh the entire page. This assumes the page is called , you can change it by providing an optional path or change it globally with the options .

You can also directly access the middleware of the underlying server instance (mini-lr.middleware) for hookup through express, connect, or some other middleware app

gulp-livereload also reveals the underlying server instance for direct access if needed. The instance is a «mini-lr» instance that this wraps around. If the server is not running then this will be .

What is livereload.js?

This repository contains a JavaScript file implementing the client side of the LiveReload protocol. It gets change notifications from a LiveReload server and applies them to the browser.

An old version of this script is also bundled with the LiveReload browser extensions, but it’s not getting updated and only serves for compatibility with very old clients.

Features:

  • Live CSS reloading
  • Full page reloading
  • Protocol, WebSocket communication
  • CSS support
  • Live image reloading (, and properties, both inline and in stylesheets)
  • Live, in-browser LESS.js reloading

Would love, but doesn’t seem possible:

live JS reloading

Using livereload.js

This script is meant to be included into the web pages you want to monitor, like this:

LiveReload 2 server listens on port and serves livereload.js over HTTP (besides speaking the web socket protocol on the same port).

A slightly smarter way is to use the host name of the current page, assuming that it is being served from the same computer. This approach enables LiveReload when viewing the web page from other devices on the network:

<script>document.write('<script src="http://'+location.host.split('')+':35729/livereload.js"></'+'script>')</script>

However, since is empty for URLs, we need to account for that:

<script>document.write('<script src="http://'+(location.host||'localhost').split('')+':35729/livereload.js"></'+'script>')</script>

LiveReload.js finds a tag that includes and uses it to determine the hostname/port to connect to. It also understands some options from the query string: , , , and .

specifies a version of the snippet, so that we can warn when the snippet needs to be updated. The currently recommended is version 1:

<script>document.write('<script src="http://'+(location.host||'localhost').split('')+':35729/livereload.js?snipver=1"></'+'script>')</script>

Additionally, you might want to specify and , which is minimum and maximum reconnection delay in milliseconds (defaulting to and ).

Alternatively, instead of loading livereload.js from the LiveReload server, you might want to include it from a different URL. In this case, add a parameter to override the host name. For example:

<scriptsrc="https://github.com/livereload/livereload-js/raw/master/dist/livereload.js?host=localhost"><script>

Signing the bundled Node.js binary

Copy:

Sign:

Verify:

AppNewsKit

(See . This is a seriously cool shit to communicate with your live users. Consider those files to be under MIT. I’ll extract and document it properly soon.)

  • Collect usage statistics
  • Deliver news to your users

Example :

    {
        "see_explanation_at": "http://help.livereload.com/kb/about-us/usage-statistics-privacy-policy",
        "messages": 
            {
                "title": "MyApp on the Mac App Store!",
                "message": "MyApp 2.1 has been released on the Mac App Store, and is on sale (50% off)! Do you want to learn more about it?",
                "id": "myapp-2.0.0-release",
                "version": ">=2.0 <3.0",
                "status": "unregistered",
                "stats": {
                    "stat.reloads": { "min": 10 }
                },
                "delay_if_nagged_within": "3d",
                "remind_later_in": "5d",
                "deliver_after": "2011-12-08 16:33:00",
                "wait_until_good_time": true,
                "delivery_on_stats": {
                    "or": {
                        "stat.reloads.last": { "within": 30 },
                        "stat.launch.first": { "within": 120 }
                    }
                },
                "random_percentage": 50,
                "primary_button_url": "http://myapp.com/mas/",
                "primary_button_title": "Visit Mac App Store"
            }
        
    }

Настройка Sublime Text 3 для веб-разработки: LiveReload, плагины, фишки

Сегодня мы рассмотрим настройку популярного редактора кода Sublime Text 3 для веб-разработки.

Плагины

emmet — плагин для скоростной верстки.

livereload — автообновление страницы.

Для корректной работы плагина LiveReload в Sublime Text 3 необходимо дописать в пользовательских настройках плагина следующую конструкцию (подробнее в видео):

sass — настроим корректную подсветку SASS в Sublime Text 3.

jade — HTML препроцессор.

gist — плагин для быстрого доступа к вашим сниппетам на GitHub.

brackethighlighter — подсветка скобок, тегов в Sublime Text 3.

autofilename — автокомплит для подключения внешних файлов в верстку.

colorhighlighter — подсветка цвета.

BufferScroll — сохранение позиции курсора в документе.


Goto-CSS-Declaration — плагин для быстрого поиска соответствующего класса в CSS, SASS, LESS.

Фишки

  • Поменяем тему на twilight.
  • Научимся множественному выделению.
  • Назначим клавиши для события reindent (хоткей для автоматического формата документа).
  • Научимся управлять числовыми значениями (Инкремент и Декремент).

Issues & Limitations

Live reloading of imported stylesheets has a 200ms lag. Modifying a CSS rule to reference a not-yet-cached file causes WebKit to lose all document styles, so we have to apply a workaround that causes a lag.

Our workaround is to add a temporary element for the imported stylesheet we’re trying to reload, wait 200ms to make sure WebKit loads the new file, then remove and recreate the rule. This prevents a flash of unstyled content. (We also wait 200 more milliseconds and recreate the rule again, in case those initial 200ms were not enough.)

Live image reloading is limited to , and styles. Any other places where images can be mentioned?

Live image reloading is limited to , , , and extensions. Maybe need to add there? Anything else?

License

The MIT License (MIT)

Copyright (c) 2014 Cyrus David

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

LiveReload для Firefox и SublimeText3. Не работает

https://youtube.com/watch?v=https%3A

Если ошибся разделом — переносите.

UPD: Починилось само собой. Тему можно удалять.

Не работает LiveReload в sublime textВыдает вот такую ошибку. Could not connect to LiveReload server. Please make sure that a compatible.

Создание расширения для Firefox. Перевод расширений Chrome на FirefoxЗдесь обсуждается процесс создания расширений для Mozilla Firefox, а также портинг из Chrome. .

Интернет работает, но Chrome и IE не открывают сайты. Firefox работает, но плохоДобрый день! У меня два компьютера получают интернет от одного роутера. На одном компьютере всё.

Method 1: Use Browser Extension

Note: Only Google Chrome supports viewing URLS, and you have to specifically enable it. If you are using other browsers and want to use URLs, add the JS code to the page as shown in the next section.

Once you have the plugin installed, start . Then, in the browser, click the LiveReload icon to connect the browser to the server.

Method 2: Add code to page

Add this code:

<script>
  document.write('<script src="http://' + (location.host || 'localhost').split(':') +
  ':35729/livereload.js?snipver=1"></' + 'script>')
</script>

Note: If you are using a different port other than you will need to change the above script.

Frameworks Integration¶

Livereload can work seamlessly with your favorite framework.

Django

For Django there is a management command included.

To use simply

  • add to your and
  • then run .

For available options like host and ports please refer to .

To automagically serve static files like the native command you have to use dj-static. (follow the simple instructions there).

Flask

Wrap Flask with livereload is much simpler:

# app is a Flask object
app = create_app()

# remember to use DEBUG mode for templates auto reload
# https://github.com/lepture/python-livereload/issues/144
app.debug = True

server = Server(app.wsgi_app)
# server.watch
server.serve()

API & Variables

livereload.listen()

Starts a livereload server. It takes an optional options parameter that is the same as the one noted above. Also you dont need to worry with multiple instances as this function will end immediately if the server is already runing.

livereload.changed(path)

Alternatively, you can call this function to send changes to the livereload server. You should provide either a simple string or an object, if an object is given it expects the object to have a property.

livereload.reload()

You can also tell the browser to refresh the entire page. This assumes the page is called , you can change it by providing an optional path or change it globally with the options .

livereload.middleware

You can also directly access the middleware of the underlying server instance (mini-lr.middleware) for hookup through express, connect, or some other middleware app

livereload.server

gulp-livereload also reveals the underlying server instance for direct access if needed. The instance is a «mini-lr» instance that this wraps around. If the server is not running then this will be .

Signing the bundled Node.js binary

Copy:

Sign:

Verify:

AppNewsKit

(See . This is a seriously cool shit to communicate with your live users. Consider those files to be under MIT. I’ll extract and document it properly soon.)

  • Collect usage statistics
  • Deliver news to your users

Example :

    {
        "see_explanation_at": "http://help.livereload.com/kb/about-us/usage-statistics-privacy-policy",
        "messages": 
            {
                "title": "MyApp on the Mac App Store!",
                "message": "MyApp 2.1 has been released on the Mac App Store, and is on sale (50% off)! Do you want to learn more about it?",
                "id": "myapp-2.0.0-release",
                "version": ">=2.0 <3.0",
                "status": "unregistered",
                "stats": {
                    "stat.reloads": { "min": 10 }
                },
                "delay_if_nagged_within": "3d",
                "remind_later_in": "5d",
                "deliver_after": "2011-12-08 16:33:00",
                "wait_until_good_time": true,
                "delivery_on_stats": {
                    "or": {
                        "stat.reloads.last": { "within": 30 },
                        "stat.launch.first": { "within": 120 }
                    }
                },
                "random_percentage": 50,
                "primary_button_url": "http://myapp.com/mas/",
                "primary_button_title": "Visit Mac App Store"
            }
        
    }

Running LiveReload

You can run LiveReload two ways: using the CLI application or by writing your own server using the API.

To use livereload from the command line:

$ npm install -g livereload$ livereload 

The commandline options are

  • or to specify the listening port
  • or to show debug messages when the browser reloads.
  • or to specify extentions that you want to observe. Example: . Removes the default extensions.
  • or to include additional extentions that you want to observe. Example: .
  • or to specify additional exclusion patterns. Example: .
  • or to poll for file system changes. Set this to true to successfully watch files over a network.
  • or to add a delay (in miliseconds) between when livereload detects a change to the filesystem and when it notifies the browser.

Specify the path when using the options.

$ livereload . -w 1000 -d

License

The MIT License (MIT)

Copyright (c) 2014 Cyrus David

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


С этим читают