Skip to content

Dynamically load and unload stylesheets #771

Closed
@catamphetamine

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 */

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