Skip to content

Dynamically load and unload stylesheets #771

Closed

Description

@catamphetamine

I'm making a website with HTML5 ajax navigation (dynamically changing page url and just replacing body content).
Therefore is the need to dynamically unload previous page styles and load new page styles.
Here is a working piece of code I'm using on my website.
It would be nice if you included something like this in your Less.js, so that we wouldn't need to hack into it again when newer versions are released.
I'm not making a pull request since this code extensively uses jQuery and I doubt that you'd like jQuery in your repo.
You may just rewrite this code the way you like it and include in the distribution.

/**  Less custom changes begin */

window.Less = {}
var Less = window.Less

Less.id = function(link)
{
    link = encodeURI(link)
    link = link.replace(/\?.*$/, '')
    return get_sheet_id('', link)
}

function get_sheet_id(title, href)
{
    return 'less:' + (title || extractId(href))
}

Less.unload_style = function(link)
{
    var head = $('head')
    head.find('style[id="' + Less.id(link) + '"]').remove()
    head.find('link[href="' + link + '"]').remove()
}

Less.load_style = function(link, callback)
{
    var style_element = $('head').find('link[href="' + link + '"]')

    // loadStyleSheet(sheet, callback, reload, remaining)
    // callback(error, root, data, sheet, { local: false, lastModified: lastModified, remaining: remaining });

    var internal_callback = function(error, parsed_document, data, sheet, info)
    {
        if (parsed_document)
            createCSS(parsed_document.toCSS(), sheet, info.lastModified)

        callback()
    }

    loadStyleSheet(style_element[0], internal_callback, false, 0)
}

/**  Less custom changes end */

Activity

  1. levithomason commented on Oct 16, 2014

    @levithomason
    Contributor

    Fixed in #2233. Please move any further conversation to that PR.

  2. added a commit that references this issue on Oct 16, 2014
  3. seven-phases-max commented on Oct 22, 2014

    @seven-phases-max
    Member

    Btw, should not we close this then? (Assuming Less is not a stylesheets manipulation library it's barely to include methods like above, and #2233 fixes this considering you load/unload stylesheets by whatever suitable methods externally (e.g. using jQuery)).

  4. levithomason commented on Oct 22, 2014

    @levithomason
    Contributor

    Agree, this is solved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions