2

If I have a userscript that I've found online, and I'd like to incorporate it into a website as a normal javascript (i.e. not userscript), how can I do that?

This seems like it would be something pretty simple but I am new to javascript and userscript, hopefully somebody can help me out.

For example, I found this userscript: "Convert UPS and FedEx Tracking Numbers to Links"...

Which will parse a page for regular expressions matching any UPS/FEDEX/USPS tracking number, and convert them to links to the respective carriers' tracking website to track that number.

This works great as a userscript, but I would like it to be automatic on the site I am working on (not require visitors to download/install a userscript).
How can I use this userscript as a regular javascript?

3 Answers 3

2

UserScripts are usually executed after the page DOM is loaded, to make sure that the page contents can be completely accessed. So, you need some kind of mechanism to achieve that. But this is a bit tricky since older versions of IE need special treatment.

Doing it manually would require about 30 lines of code. Libraries like jQuery offer a ready() method like so:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {

    // put userScript here

});
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This solved the issue.. I guess the script was executing before the rest of the page loaded.
2

It should just be a matter of linking it like any other Javascript file:

Save it as foo.js, then in your html,

<body>
<!-- body code here -->
<script src="foo.js"></script>
</body>

3 Comments

Thanks.. I had done that but it was not working, turned out the problem was that it was executing before the rest of the page.
jmiller, It would not do that if the script was placed as this answer shows... Just before the closing </body> tag. Placing scripts here is a common performance boost, also.
I see.. yes, I had it in an included header file that also contains code that needs to execute before the page is loaded.. is there any advantage to this setup over using the jquery ready method?
1

You can just put it in a JS file and include the file in your page.

UserScripts contain normal Javascript code, but are executed by a plugin rather than being on the page.

1 Comment

Thanks.. I had done that but it was not working, turned out the problem was that it was executing before the rest of the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.