How to inject a script before page load on a website?
Using Requestly’s Insert Scripts Rule, you can make on-the-fly changes to a webpage content. It allows you to automate, scrape & change webpages behaviour without needed to access the page source code.
Use Cases
- Inject popular libraries or hosted scripts or execute custom code-snippet before or after page load using a simple rule builder.
- Give custom theme to Twitter or any other website. Remove/hide unwanted sections from the page.
- Debugging CSS (see example below).
Use Requestly browser extension to insert script before page load
To insert script before page load you can use Requestly’s Insert script rule.
- Install Requestly’s browser extension.
- Click Create your first rule and go to Insert Script and click Create Rule.
- Enter the source URL condition.
- Source Condition: Source condition is where you set criteria for the rules. You can use
URL
,Host
, orPath
withRegex
,Contains
,Wildcard
, orEquals
to match the source request. Learn more about source conditions here. - Script Language: The specific script language (JS/CSS) that needs to be inserted.
- Script Source: Source Code or URL of the script that needs to be inserted.
- Script Load Time: When is the script loaded in the webpage. (Before Page Load/After Page Load)
- Script Start/End Logs: Turn it off if you don’t want to show start end logs of the script.
Inserting Script with Attributes
Inserting a script with some attributes is a common requirement. Sometimes you need to use boolean attributes like defer
for external scripts to instruct the browser to download the script but execute it after the page loads. Similarly, there are other attributes with specific purposes like async
, nomodule
, crossorigin
, integrity
, referrerpolicy
, etc. and there are other data-*
attributes as well. Requestly comes equipped with a way to modify these rules while inserting scripts into a page. Below are the steps to define attributes:
- Create new rule – Insert Script Rule
- Define source condition as required.
- Select the Code Source as Code or URL.
- In the case of URL – Enter the URL of the file given and add attributes in the field where <script> tag is shown.
- In case of Code – Enter your custom code in the provided space and edit the <script> to add attributes.